【问题标题】:Button.onClick.AddListener(() => ItemButton(i)) Applies the same i value [duplicate]Button.onClick.AddListener(() => ItemButton(i)) 应用相同的 i 值 [重复]
【发布时间】:2020-06-28 23:10:43
【问题描述】:

所以,我在我的商店系统上工作,我想让它在玩家按下按钮时被选中(我需要知道我按下的按钮的 ID

void Awake()
{
    //Cycle through all the ShopItems
    for (int i = 0; i < shopItemsList.Count; i++)
    {
        go = Instantiate(ItemTemplate, ShopScrollView);
        go.GetComponent<Button>().onClick.AddListener(() => ItemButton(i));
        go.transform.GetChild(0).GetComponent<TextMeshProUGUI>().text = shopItemsList[i].itemName;

        if (!shopItemsList[i].isPurchased)
        {
            go.transform.GetChild(1).gameObject.SetActive(true);
        }
        else if (shopItemsList[i].isChosen)
        {
            go.GetComponent<Image>().color = new Color32(164, 0, 0, 255);
        }
            go.transform.GetChild(1).GetChild(0).GetComponent<TextMeshProUGUI>().txt = shopItemsList[i].price.ToString() + "$";
        }
    }


    void ItemButton(int itemName)
    {
        Debug.Log(itemName);
    }
}

因此,当我在 Unity 中按下播放按钮时,一切正常(每个项目都有其统计信息),但 所有按钮的值都相同,等于 12(“for”循环的最后一次迭代)

【问题讨论】:

    标签: c# unity3d scripting


    【解决方案1】:

    这就是 C# 中捕获和 for 循环的工作方式(例如,您可以阅读更多关于它的信息 herehere)。引入临时变量,给它赋值i并在lambda中使用:

     for (int i = 0; i < shopItemsList.Count; i++)
        {
            var temp = i;
            go = Instantiate(ItemTemplate, ShopScrollView);
            go.GetComponent<Button>().onClick.AddListener(() => ItemButton(temp));
            ....
        } 
    

    【讨论】:

    • 如果之前回答过这个问题,我们不应该将其标记为重复而不是再次回答吗? ;)
    猜你喜欢
    • 1970-01-01
    • 2014-03-03
    • 2011-10-15
    • 2012-09-02
    • 1970-01-01
    • 2013-04-26
    • 2017-02-15
    相关资源
    最近更新 更多