P
P
piffo2020-05-08 01:57:03
C++ / C#
piffo, 2020-05-08 01:57:03

Optimizing a bunch of if?

string puk = SceneManager.GetActiveScene().name;
        if (puk == "Level1")
            levelNum = 1;
        if (puk == "Level2")
            levelNum = 2;
        if (puk == "Level3")
            levelNum = 3;
        if (puk == "Level4")
            levelNum = 4;
        if (puk == "Level5")
            levelNum = 5;

How it can be optimized not to write if every time?
PS something tells me that loops and arrays will come in handy here)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Timur Pokrovsky, 2020-05-08
@piffo

levelNum = int.Parse(puk[puk.Length - 1]);

A
ATauenis, 2020-05-08
@ATauenis

levelNum = int.Parse(puk.Substring("Level".Length));

And be sure to make sure that the exception is caught in time if suddenly there is an error in the line.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question