Problem with foreach loop giving values to a button in Unity

后端 未结 2 1765
终归单人心
终归单人心 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条回答
  •  闹比i
    闹比i (楼主)
    2021-01-29 04:22

    You've created a closure on a loop variable. A common pitfall, for sure. A suitable explanation and remedy for this kind of problem already exists on StackOverflow.

    When you use the symbol i, it is essentially a reference to the one and only i that existed outside of your loop. Its value, by the time any of the listeners get invoked, will be the value it had at the end of the loop, which, in your case, would be the number of levels you have.

    To avoid this, you need to use the value of i, not a reference to the variable. You can do this by creating a new variable that will have scope unique to one iteration of the loop and passing in that new variable's value. Basically a copy of i is what you need.

    The essence of the necessary change would be:

    int i = 0;
    foreach(GameObject level in levels)
    {
        int copy_of_i = i;
        level.GetComponent

提交回复
热议问题