Unity 5修复了侦听器调用

时间:2015-03-17 10:03:54

标签: c# unity3d listener unity3d-gui

我在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将parm作为parm的最后一个&#34; str&#34;值foreach cycle)。

1 个答案:

答案 0 :(得分:0)

我认为你的问题与此有关: 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++;
}