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:
-
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); } }
-
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*.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: