0

I get a really weird behavior with this piece of code

for (int i = 0; i < 2; ++i)
            optionContent.GetChild(i).GetComponent<Button>().onClick.AddListener(() => SetOption(i, true));

The weird behavior is that all listeners gets attached the function SetOption(2, true)

I think the 2 comes from the fact that at the end of the for loop, i is set to 2, but still, why is this the behavior and is there a way to get around this?

Edit:

I played around for a bit and I think the problem is that delegates store variable references as references, not values

int x = 0;
Action a = delegate { int b = x; Console.WriteLine(b); };
x = 10;
a();

The above code will print 10, instead of 0. How do I make it to use the value 0?

Shawn Li
  • 419
  • 3
  • 17
  • 1
    What if you use int j = i? –  Oct 13 '17 at 02:22
  • 1
    You seem to have understood me wrong. for `(int i = 0; i < 2; ++i) {int j = i; optionContent.GetChild(j).GetComponent –  Oct 13 '17 at 02:39
  • 1
    I'm having trouble finding the best duplicate candidate, but you're closing over the loop variable `i`. @someone has given you the correct recourse, however. Create another variable within the loop, and use that within your closure. – Anthony Pegram Oct 13 '17 at 02:42
  • see also https://stackoverflow.com/questions/8898925/is-there-a-reason-for-cs-reuse-of-the-variable-in-a-foreach/8899347#8899347 – Eric Lippert Oct 13 '17 at 05:40

0 Answers0