我试图在Repeat(int value)中传递单击按钮的索引,并写成这样-
    gp.GetComponentInChildren().onClick.AddListener(()=>
    重复(rep));
但是,当我单击任何按钮时,我得到了所有按钮的最后一个索引。
我想知道有什么办法可以传递在Repeat()中单击的那个按钮的索引吗?


void chatDialogs() {

        foreach (Transform child in this.transform) {
            GameObject.Destroy (child.gameObject);
        }

        for (int i = 5; i > 0 ; i--) {
            int currentStep = Laststep - i;
            if (currentStep >= 0) {
                 gp = (GameObject)Instantiate (playerPreFab);
                 gp.transform.SetParent (this.transform);
            }
            gp.GetComponentInChildren<Button> ().onClick.AddListener(() =>
            Repeat(**transform.GetSiblingIndex()**));
        }
    public void Repeat(int speakstep) {
        Application.ExternalCall("textspeak", speakstep);
    }


在Repeat()的语音步骤对象中,应传递所单击的按钮索引,但它会获得我单击的每个按钮中的最后一个索引。

最佳答案

我认为您可以执行以下操作:

AddButtonListener(gp.GetComponentInChildren<Button> (), i);


在您的for循环中,
AddButtonListener定义为:

void AddButtonListener(Button b, int index)
{
    b.onClick.AddListener(()=>{Repeat(index)});
}


这样,您就可以在侦听器函数中捕获按钮索引(但是我不确定该模式的正确名称是什么),而我实际上没有运行它就写了它。希望您现在有足够的信息以使其正常运行。

10-08 07:09
查看更多