2

I'm very new to unity and i was trying to add a button for each level/scene with an event that laods the scene of it. The code below does add the button and gives it the right text but the onClick event keeps getting stuck on index 2 with the following error message when pressed: 'scene with build index: 2 couldn't be loaded because it has not been added to the build settings.'.

At this moment i have 2 scenes, a menu and one level. I started the loop from index 1 so the menu doesn't get added. But even when i include the menu and click on that button it states the same error message with index 2.

Why does every button try to load the scene with buildindex 2? All help is appriciated.


//button grid public Transform grid;

//prefab button
public GameObject button;

//Loop over all scenes starting from the index of the first level
//for each scene make a button, change it's text to the index number
//add onclick event to the new button to start the selected level
private void Start()
{
    for (int i = 1; i < SceneManager.sceneCountInBuildSettings; i++)
    {
        GameObject go = Instantiate(button, grid);
        Button btn = go.GetComponent<Button>();

        btn.GetComponentInChildren<TextMeshProUGUI>().text = i.ToString();
        btn.onClick.AddListener(() => {
            SceneManager.LoadScene(i);
        });     
    }
} 

ruben
  • 97
  • 10

1 Answers1

3

You are facing the closure problem. This problem is explained here

for (int i = 1; i < SceneManager.sceneCountInBuildSettings; i++)
{
    int index = i;
    GameObject go = Instantiate(button, grid);
    Button btn = go.GetComponent<Button>();

    btn.GetComponentInChildren<TextMeshProUGUI>().text = i.ToString();
    btn.onClick.AddListener(() => {
        SceneManager.LoadScene(index);
    });     
}
Hellium
  • 7,206
  • 2
  • 19
  • 49