LoadScene by index doesn't work properly

Hello!

So, I have a simple loop. It sets up my buttons that simply load different scenes.

        for(int i = 0; i < 2; i++)
        {
            Debug.Log (i);

            GameObject obj = (GameObject)Instantiate (levelBtn);
            obj.GetComponent<Button> ().onClick.AddListener (() => LoadLevel(i+1));
        }

Dont pay attention for LoadLevel function. It has just code:

    public void LoadLevel(int name)
    {
        SceneManager.LoadScene (name);
    }

Due to debugging I get 0 and 1, as I expected. That is fine. But I want to load scenes that higher than 0 (because 0 is a menu so far). So, that is why I am adding 1 to i when I add listener. I start play mode, click the first button, and the error appears. It says:

Why 3? It shouldn’t load scene with index 3… It should load 2. Why? Bug? I tried to remove +1. Now the first button loads the scene #2, but debugging shows me that i is 0 (should load the scene #1). Moreover, I tried to decrease i by 1 (i-1). Now the button #1 loads the scene #1, but the button #2 loads the scene #1 as well. I am confused. 0_o

P.S. Build Scene Settings are proper: 0 - menu; 1 - scene1, 2 - scene2

That’s because ‘i’ will be captured for the lambda expression, not its value.
Quick workaround would be to declare a variable which is local to the loop and assign i to it, then use the local variable in the lambda.

1 Like

It works. Thanks a lot!