- Home /
Adding listener to buttons through script results in array out of index
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!
Seems like you are adding 4 listeners to one button in your example. I would assume you need to create the new button inside of the loop.
Yes, I create a new button for each loop. I forgot to include that. Sorry.
Answer by dppc · Feb 03, 2016 at 07:54 PM
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); });
Your answer
Follow this Question
Related Questions
Call a variable from each game object in an array? 1 Answer
Changing texture of pressed button in array 1 Answer
Button array c# 0 Answers
reference array item relative to selectiongrid button 0 Answers