[SerializeField] List<Button> Buttons;
void Start()
{
for (int i = 0; i < Buttons.Count; i++)
{
Buttons[i].onClick.AddListener(() => DoThing(i));// can't hold i variable
//when click the each button result is always 3
// i want 0,1,2
print(i); // 0,1,2
}
}
public void DoThing(int value)
{
print(value);
}
I want to use i as parameter of a button click event action but each button always prints 3. Instead of using i Buttons[i].onClick.AddListener(() => DoThing(2)) is working fine. how use i as parameter
>Solution :
In your code, DoThing will capture the variable i (and not its value) and will only get the value of i when you invoke onClick.
Copy the value of a changing variable to the scope where the closure is defined
[SerializeField] List<Button> Buttons;
void Start()
{
for (int i = 0; i < Buttons.Count; i++)
{
var iLocal = i;
Buttons[i].onClick.AddListener(() => DoThing(iLocal));
}
}
public void DoThing(int value)
{
print(value);
}
This fix makes sure that when you get the context where the action was created, iLocal will hold the value corresponding to the index of the button in the list.