UI button listener AddListener not working in a loop

goo*_*odm 0 c# user-interface unity-game-engine

I've got problem with UI listener. I try to assign click listener to the method in for loop for UI, but every time I've got last option selected.

public Button[] options;

void Start () 
{
    for(int i = 0; i < options.Length; i++)
    {
        options[i].onClick.AddListener(()=> {OptionPressed(i);});
    }
}

private void OptionPressed(int i)
{
    print (i);
}
Run Code Online (Sandbox Code Playgroud)

It's always print 3. My question is why? and also why 3 while there is only 3 buttons, so it should be 2?

Mat*_*usz 5

It prints 3 because you're not boxing the value of i, it's value is getting re-written each time it iterates.
To fix this try doing something like this :

for ( int i = 0; i < options.Length; ++i )
{
    int j = i;
    options[i].onClick.AddListener( () => { OptionPressed(j); } );
}
Run Code Online (Sandbox Code Playgroud)

Check the difference

  • 这个问题已经被问了很多次,现在应该作为重复关闭,除非问题的脚本中有另一个问题。 (3认同)