DEV Community

Piler
Piler

Posted on

[Unity] Delegate and loop related issue

    void Start()
    {
        for (int i = 0; i < 3; i++)
        {
            button.onClick.AddListener(() => Foo(i));
        }
    }

    void Foo(int i)
    {
        Debug.Log(i);
    }
Enter fullscreen mode Exit fullscreen mode

When you write code like this, you expected the output is

0
1
2
Enter fullscreen mode Exit fullscreen mode

but the result is

3
3
3
Enter fullscreen mode Exit fullscreen mode

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);
    }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)