void Start()
{
for (int i = 0; i < 3; i++)
{
button.onClick.AddListener(() => Foo(i));
}
}
void Foo(int i)
{
Debug.Log(i);
}
When you write code like this, you expected the output is
0
1
2
but the result is
3
3
3
The reason is when using delegate, variable is captured by reference. (Closure and Captured Variable Behavior)
Solution:
void Start()
{
for (int i = 0; i < 3; i++)
{
int temp = i;
button.onClick.AddListener(() => Foo(temp));
}
}
void Foo(int i)
{
Debug.Log(i);
}
Top comments (0)