复制
收藏
提问
简洁

for (int i = 0; i < (uiParent.childCount)-1; i++) { int ButtonIndex = i; Buttons[i].onClick.AddListener(() => ShowIntroduction(ButtonIndex)); } }public void ShowIntroduction(int i) { EIText.text = EquipmentIntroduction[i]; print(i); }按下第一个按钮,为何print(i)的值会是3

3月前
全网
文档
学术
百科
知识库
时间不限
自动
回答简洁模式
深入研究一些

在C#编程中,当您使用for循环为多个按钮添加点击事件监听器时,如果直接在循环体内部使用变量i,由于闭包的原因,所有的监听器最终都会引用循环结束后i的最终值。在您提供的代码示例中,i的值在循环结束时是(uiParent.childCount)-1,因此所有按钮的点击事件都会调用ShowIntroduction((uiParent.childCount)-1),这就是为什么print(i)的值会是3的原因。

要解决这个问题,您可以通过创建一个匿名方法或者使用Action委托来捕获循环中i的当前值。以下是两种可能的解决方案:

  1. 使用匿名方法捕获变量值

    for (int i = 0; i < (uiParent.childCount) - 1; i++)
    {
        Buttons[i].onClick.AddListener(delegate { ShowIntroduction(i); });
    }
    
  2. 使用Action委托

    Action<int> showIntroAction = null;
    for (int i = 0; i < (uiParent.childCount) - 1; i++)
    {
        showIntroAction = (index) => ShowIntroduction(index);
        Buttons[i].onClick.AddListener(showIntroAction);
    }
    

这两种方法都能够确保每个按钮的点击事件都能正确地使用循环中i的当前值。15

你觉得结果怎么样?
为什么print(i)输出的值不是0?
C#中ButtonIndex变量的作用是什么?
如何在Unity中为按钮添加点击事件?
Unity中childCount属性的作用是什么?
如何在Unity中使用List存储数据?
为什么在for循环中ButtonIndex的值会改变?

以上内容由AI搜集生成,仅供参考

在线客服