我有一些我不明白的行为。虽然展开的循环工作正常!循环抛出IndexOutOfRangeExceptions。调试显示有0..9 teamButtons和0..9卡c [i]。 :(
private void Awake()
{
InitCards();
// This works!
teamButtons[0].onClick.AddListener(() => SetCard(c[0]));
teamButtons[1].onClick.AddListener(() => SetCard(c[1]));
teamButtons[2].onClick.AddListener(() => SetCard(c[2]));
teamButtons[3].onClick.AddListener(() => SetCard(c[3]));
teamButtons[4].onClick.AddListener(() => SetCard(c[4]));
teamButtons[5].onClick.AddListener(() => SetCard(c[5]));
teamButtons[6].onClick.AddListener(() => SetCard(c[6]));
teamButtons[7].onClick.AddListener(() => SetCard(c[7]));
teamButtons[8].onClick.AddListener(() => SetCard(c[8]));
// This yields an IndexOutOfRangeException
for (int i = 0; i < 9; ++i)
{
teamButtons[i].onClick.AddListener(() => { SetCard(c[i]); });
}
}
答案 0 :(得分:13)
您正在捕获lambda表达式中的变量 i
。当执行lambda表达式时,它将使用i
的“当前”值 - 它始终为9.您想要捕获变量的副本 ...您可以在循环中引入一个新变量:
for (int i = 0; i < teamButtons.Length; i++)
{
int index = i;
teamButtons[i].onClick.AddListener(() => SetCard(c[index]));
}