0

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);
}

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

Programmer
  • 121,791
  • 22
  • 236
  • 328
goodm
  • 7,275
  • 6
  • 31
  • 55

1 Answers1

6

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); } );
}

Check the difference

mrogal.ski
  • 5,828
  • 1
  • 21
  • 30
  • 3
    This question has been asked so many times that it should now be closed as a duplicate unless there is another problem in the script from the question. – Programmer Apr 26 '17 at 13:34
  • 1
    Thanks @m.rogalski , I should think about it. – goodm Apr 26 '17 at 13:37