0

我在 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”值作为参数)。

4

1 回答 1

0

I assume your problem is related to this: Access to Modified Closure

try to work with copy of the string

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++;
}
于 2015-03-17T10:31:35.793 回答