c# - 如何提供实例动态创建的点击按钮的索引?

标签 c# unity3d

  1. 我试图在 Repeat(int value) 中传递点击按钮的索引并写下这个 - gp.GetComponentInChildren ().onClick.AddListener(() => 重复(rep));

  2. 但是当我点击任何按钮时,我得到了所有按钮的最后一个索引。 我想知道有什么办法可以传递我在 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() 的 speakstep 对象中,点击的按钮索引应该被传递,但它获取我点击的每个按钮的最后一个索引。

最佳答案

我认为你可以这样做:

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

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

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

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

关于c# - 如何提供实例动态创建的点击按钮的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56330152/

相关文章:

c# - 空(非空)对象检测

c# - LINQ:如何在选择期间转换查询结果?

c# - 不从文件反序列化

c# - 使用图像参数时 Unity 连接到 Dall-E API?

c# - Unity3D连接MySQL报错

c# - 泛型 <T> Unity C#

c# - Ajax TimerControl 和实例变量?

c# - Winrt Hubsection 中的引用控件

c# - 迁移到 Qualcomm 增强现实时出现 ARCamera 问题 vuforia-unity-android-ios-3-0-6

android - 在 Android 中构建时,Unity3D 文本不显示