首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何提供实例动态创建的被点击按钮的索引?

如何提供实例动态创建的被点击按钮的索引?
EN

Stack Overflow用户
提问于 2019-05-28 01:18:32
回答 1查看 180关注 0票数 2

我试图在(int值)中传递被点击按钮的索引,并写成这个- gp.GetComponentInChildren ().onClick.AddListener(() => Repeat(rep));

  1. But )当我点击任何一个按钮时,我得到了该按钮的最后一个索引。我想知道有没有什么方法可以传递我在Repeat()中点击的那个按钮的索引?

代码语言:javascript
复制
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()的speakstep对象中,应该传递被点击按钮的索引,但它获取我所点击的每个按钮的最后一个索引。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-28 02:11:21

我认为你可以这样做:

代码语言:javascript
复制
AddButtonListener(gp.GetComponentInChildren<Button> (), i);

for循环中,当AddButtonListener被定义为:

代码语言:javascript
复制
void AddButtonListener(Button b, int index)
{
    b.onClick.AddListener(()=>{Repeat(index)});
}

通过这种方式,您可以在侦听器函数中捕获按钮索引(但我不确定此模式的正确名称是什么),并且我并没有实际运行它就编写了这段代码。希望你现在有足够的信息让它工作。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56330152

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档