【问题标题】:Unity 5 fix Listener callsUnity 5 修复监听器调用
【发布时间】:2015-05-19 17:05:15
【问题描述】:

我在使用 Unity 5 中运行时生成的按钮时遇到问题。 按钮创建正确,但听众有一些问题。 我使用此代码创建按钮:

 foreach (string str in _scene.PDF_ITEMS)
    {
        button = (GameObject)Instantiate(_primitive);
        button.GetComponent<Button>().onClick.AddListener(() => OpenPDF(str));
        button.GetComponentInChildren<Text>().text = str;
        button.GetComponent<Transform>().SetParent(this.transform, false);
        GetComponent<RectTransform>().anchorMin = Vector2.zero;
        GetComponent<RectTransform>().anchorMax = Vector2.one;
        width++;
    }

这是 OpenPDF 函数:

private void OpenPDF(string name)
{
    string comandType;
    if (_scene.isCurrent(ArrayUtility.IndexOf<string>(_scene.PDF_ITEMS, name))) comandType = ControllerScene.IN_CLOSE_ITEM + "";
    else comandType = ControllerScene.IN_OPEN_ITEM + "";
    _inj.addComand(comandType, "" + (ArrayUtility.IndexOf<string>(_scene.PDF_ITEMS, name)));
}

问题是,当我播放场景并单击按钮时,它会触发我创建的最后一个按钮的侦听器(函数 OpenPdf 将 foreach 循环中的最后一个“str”值作为参数)。

【问题讨论】:

    标签: c# unity3d listener unity3d-gui


    【解决方案1】:

    我认为您的问题与此有关: Access to Modified Closure

    尝试使用字符串的副本

    foreach (string str in _scene.PDF_ITEMS)
    {
        string strCopy = string.Copy(str);
        button = (GameObject)Instantiate(_primitive);
        button.GetComponent<Button>().onClick.AddListener(() => OpenPDF(strCopy));
        button.GetComponentInChildren<Text>().text = str;
        button.GetComponent<Transform>().SetParent(this.transform, false);
        GetComponent<RectTransform>().anchorMin = Vector2.zero;
        GetComponent<RectTransform>().anchorMax = Vector2.one;
        width++;
    }
    

    【讨论】:

    • 好的,问题是我给了str obj指针,然后当我修改te str时,我修改了与obj相关的所有项目?
    • @MaGiiK,有点像。 Foreach 修改了闭包捕获的引用
    猜你喜欢
    • 2017-12-08
    • 2014-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-20
    • 2011-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多