For loops or nested if statement? assignments every frame?

The question is:
in the code you use an update method for loops and assignments:

var nextState = currentState.GetNextStates();

and a for loop that iterates with indexes of an array;

Does that mean that we are doing this every frame? Wouldn’t it be better to have something like:

    if (Input.GetKeyDown(KeyCode.Alpha3))
    {
        nextState = currentState.GetNextStates();
        if (nextState.Length > 2)
        { 
            currentState = nextState[2];
            textComponent.text = currentState.GetStateStory();
        }
    }

and so forth…
in this case assignments only happen when something really happens, like button presses?

Hi urdenster,

Welcome to our community! :slight_smile:

That’s a good question, and there is no definite answer. It depends on your goal. Assuming you have got several states, you would have to write three if-statements with the same lines of code over and over again. Redundancy is something we want to avoid as it makes the code longer than necessary.

Executing var nextState = currentState.GetNextStates(); each frame does not have any noticeable impact on the performance because we do not make the computer calculate anything complex. Nevertheless, if we can avoid executing code, we usually do that. This is the first real project in our course, though, which is why Rick opted for a straightforward solution.

Please feel free to use your code. :slight_smile:


See also:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms