Assigning different buttons click events to the same function with a parameter dynamically
I've faced with the problem and been trying to solve it for almost an hour. I'm sharing this just in case anyone may face with the same problem. To explain the question and answer more clearly here is an example:
1) Let's say you create some button objects dynamically and add pile them up in a List:
private void CreateButtons(int length)
{
for (int i = 0; i < length; i++)
{
var newButton = Instantiate(buttonPrefab);
buttonList.Add(newButton);
}
}
2) Then you want to assign same function to different buttons but with different parameters:
Here is the assigned method:
private void Test(int a)
{
print(a);
}
And here is the assigning loop:
private void AssignClickEvents()
{
for (int i = 0; i < buttonList.Count; i++)
{
buttonList[i].GetComponent<Button>().onClick.AddListener(() => { Test(i); });
}
}
The problem with the above code is that when a button is clicked it won't give you 0,1,2... etc. All buttons will give you the same value which is last assigned value of loop parameter 'i'. Check answer for solution:
Answer by unity_WPzfLehdpNGaDQ · Feb 20, 2020 at 01:15 PM
I don't know the excat reason behind this but to get things work you need to use a local variable for function parameter. Here is the code:
private void AssignClickEvents()
{
for (int i = 0; i < buttonList.Count; i++)
{
int a = i;
buttonList[i].GetComponent<Button>().onClick.AddListener(() => { Test(a); });
}
}
I hope it helps!
Thanks for this, made no sense why my code was not working. Cheers :)
Your answer
Follow this Question
Related Questions
How to use the name of the button as a value of a variable? 0 Answers
how to make sound settings button? 1 Answer
clicking button using script? 1 Answer
How to move images onto a canvas 0 Answers