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