【问题标题】:Assigning different buttons click events to the same function with a parameter dynamically使用参数动态地将不同的按钮单击事件分配给同一函数
【发布时间】:2020-06-04 19:59:44
【问题描述】:

我遇到了这个问题,并尝试解决了将近一个小时。我分享这个以防万一有人遇到同样的问题。为了更清楚地解释问题和答案,这里举个例子:

1) 假设您动态创建了一些按钮对象并将它们添加到列表中:

    private void CreateButtons(int length)
    {
        for (int i = 0; i < length; i++)
        {
            var newButton = Instantiate(buttonPrefab);

            buttonList.Add(newButton);
        }
    }

2)然后你想为不同的按钮分配相同的功能,但参数不同:

这是分配的方法:

    private void Test(int a)
    {
        print(a);
    }

这里是分配循环:

    private void AssignClickEvents()
    {
        for (int i = 0; i < buttonList.Count; i++)
        {
            buttonList[i].GetComponent<Button>().onClick.AddListener(() => { Test(i); });
        }
    }

上面代码的问题是,当一个按钮被点击时,它不会给你 0,1,2... 等等。所有按钮都会给你相同的值,这是循环参数 'i 的最后分配值'。检查答案以获得解决方案:

【问题讨论】:

    标签: unity3d events button onclick


    【解决方案1】:

    我不知道这背后的确切原因,但要让事情正常工作,您需要使用局部变量作为函数参数。代码如下:

        private void AssignClickEvents()
        {
            for (int i = 0; i < buttonList.Count; i++)
            {
                int a = i;
                buttonList[i].GetComponent<Button>().onClick.AddListener(() => { Test(a); });
            }
        }
    

    希望对你有帮助!

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-29
    • 1970-01-01
    • 2010-10-08
    • 1970-01-01
    • 2020-04-29
    相关资源
    最近更新 更多