Problem with foreach loop giving values to a button in Unity

后端 未结 2 1797
终归单人心
终归单人心 2021-01-29 03:45

I\'m trying to do a Candy Crush-like map for my game in Unity, I\'m trying to gather all the buttons in an array and then set its onclick property so when I click on them I get

2条回答
  •  执念已碎
    2021-01-29 04:23

    I think the problem is the lambda expression: () => SceneManager.LoadScene(i + 1)

    you it is not the value of i, but instead the variable i, which will get incremented again over the other iterations so when you click on it SceneManager.LoadScene(i + 1); gets called, but i is now 25 or whatever your level number is.

    Create a temporary variable directly before it so each lambda expression gets their own variable int tmp = i; level.GetComponent().onClick.AddListener(() =>SceneManager.LoadScene(tmp + 1));

提交回复
热议问题