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?
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)