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?