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");
}
}
'유니티' 카테고리의 다른 글
[유니티] MMF Player 이용해서 화면 깜빡임(Flash) 넣기 (0) | 2023.05.12 |
---|---|
[유니티] MMF Player로 화면 쉐이크 넣기 (0) | 2023.05.12 |
[유니티] 게임오브젝트 이동 시 배경 무한 복사 (0) | 2023.04.19 |
[유니티] 구글인앱리뷰 설정하기 (0) | 2023.04.15 |
Particle System으로 만들어진 GameObject의 Rotation이 안되는 문제 (0) | 2023.03.28 |