유니티

For Loop에서 AddListener 사용!

HorseDragon 2023. 4. 26. 20:03

For Loop에서 AddListener를 썼더니 가장 마지막 숫자로 초기화된다.

코드 자체는 분명 오류가 없는데, 결국 AddListener가 bowUpButtons.Length 의 값으로 초기화.

void bowEquipButtonInitialize()
    {
        for (int i = 0; i < bowUpButtons.Length; i++)
        {            
            bowEquipButtons[i].onClick.AddListener(() => bowEquip(i));
            Debug.Log($"Bow Equip button {i} is ready");
        }
    }

찾아보니, closure problem 이라는게 있다고 한다.

for 문에서 AddListener 람다식은 주의해야한다. (AddListener for loop) 클로저 Closure problem - 맨텀 (tistory.com)

 

for 문에서 AddListener 람다식은 주의해야한다. (AddListener for loop) 클로저 Closure problem

#. 문제는 무엇인가? 버튼을 배열로 선언해놓고 for문에서 AddListener로 할당하려고 했는데, 모두 마지막 값으로 초기화되는 현상이 있었다. for (int i = 0; i < Btns.Length; i++) { Btns[i].onClick.AddListener(() =>

mentum.tistory.com

closures - Captured variable in a loop in C# - Stack Overflow

 

Captured variable in a loop in C#

I met an interesting issue about C#. I have code like below. List<Func<int>> actions = new List<Func<int>>(); int variable = 0; while (variable < 5) { actions.Add((...

stackoverflow.com

 

그래서 결국 아래와 같이 바꾸었더니 문제가 해결됨!!

void bowEquipButtonInitialize()
    {
        for (int i = 0; i < bowUpButtons.Length; i++)
        {
            int temp = i;
            bowEquipButtons[temp].onClick.AddListener(() => bowEquip(temp));
            Debug.Log($"Bow Equip button {i} is ready");
        }
    }