我试图在 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() 的 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/