How does the For Loop Iterate

Hello!

I am confused with the concept of how the For Loop iterates.

I get that the “for” statement will increase the value of the variable “index” (in this case) until the condition becomes false.

What I am thinking is that if the value of “index” increases then won’t the only option be, for example, “index = 2” therefore making “index = 0” and “index = 1” nonexistent because the “for” statement rose the value of “index” up to “2”?

I maybe though that how it works could be:

As the statement is run and, for example, nextStates.Length = 2 it will create multiple versions of the “if” statement below it, each corresponding to one of the options “index=0”, “index=1”, “index=2”.

I just don’t understand how the For loop works conceptually.

Here is the code in question:

    var nextStates = state.GetNextStates();

    for (int index = 0; index < nextStates.Length; index++)
    {
        if (Input.GetKeyDown(KeyCode.Alpha1 + index))
        {
            state = nextStates[index];

            textComponent.text = state.GetStateStory();
        }
    }
1 Like

That’s pretty much how that works, but it doesn’t look at them at the same time, just want to clarify in case there’s some sort of confusion. If you’d like a visual representation of how that would look without a loop, it would look similar to this:

       if (Input.GetKeyDown(KeyCode.Alpha1)) {
            //Do Something
        }
       if (Input.GetKeyDown(KeyCode.Alpha2)) {
            //Do Something
        }
       if (Input.GetKeyDown(KeyCode.Alpha3)) {
            //Do Something
        }

As you said, multiple versions but it looks at them each at a time.

Thanks for the response Yee!

Off of that though, when you say:

Does it cycle through all of them in one frame or does it do one option per frame? In the latter possibility, would it then mean that if I pressed an option it was not looking at frame perfectly it would not register my button press?

In this particular case, since the method is called during Update (which runs once per frame), the loop cycles through all of them in a single frame. You can change that if you implement a timer or use a coroutine.

2 Likes

Gotcha, Now I understand how it works! Thank you!

1 Like

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

Privacy & Terms