Hi
I have a function that creates a few buttons that need to be generated at runtime and I then need to assign their click event by a script. Now this doesn’t work. I assign them a function that needs an int. The code I use for this is as simple as this:
for (int i = 0; i < tabs.Length; i++)
{
Button newButton = Instantiate(tabButton);
newButton.transform.SetParent(tabButtonsHolder);
newButton.onClick.AddListener(() => { ChangeTab(i); });
}
Now this doesn’t work. Whenever I click the button I just get an Array index out of range error. I also have a debug.log message that displays the index number that was given to the button. So I have 4 objects in an array so the last object has the index of 3. And for some reason, EVERY button has the index of 4. It always goes one number above.
I have no idea what is going on. Any help with this is greatly appreciated!
dppc
2
You’re running into variable capturing.
To avoid that, replace the last line of your loop with these two lines:
int n = i;
newButton.onClick.AddListener(() => { ChangeTab(n); });