[英]Unity3d c#. onClick.AddListener() works once
There's a void in the script, which reloads Canvas. 脚本中有一个空白,它重新加载Canvas。 The Canvas contains the Button object.
Canvas包含Button对象。 I attach the reload void with the script.
我用脚本附加了reload void。
using UnityEngine;
using UnityEngine.UI;
public class Trashscript : MonoBehaviour {
public GameObject Temp;
private GameObject Active;
int Counter;
void Start()
{
Menu();
}
void Menu()
{
Counter++;
if (Active != null) Destroy(Active);
Active = Instantiate(Temp);
GameObject.Find("Text").GetComponent<Text>().text = Counter.ToString();
GameObject.Find("Btn").GetComponent<Button>().onClick.AddListener(Menu);
}
}
First call (from Start
) works fine the "Text" element shows "1". 第一次调用(从
Start
)工作正常,“Text”元素显示“1”。 After clicking the "Btn" Canvas reloads, but there isn't any "Text", and "Btn" doesn't work (onClick event do nothing). 单击“Btn”Canvas重新加载后,但没有任何“文本”,“Btn”不起作用(onClick事件什么都不做)。
Help. 救命。
I can't tell what your code is doing but each time the Button
is clicked, Menu
function is called which leads to GetComponent<Button>().onClick.AddListener(Menu)
being called again. 我无法分辨你的代码在做什么,但每次单击
Button
,都会调用Menu
函数,这会导致再次GetComponent<Button>().onClick.AddListener(Menu)
。
You have to move GetComponent<Button>().onClick.AddListener(Menu)
out of the Munu
function and into the Start()
function. 您必须将
GetComponent<Button>().onClick.AddListener(Menu)
移出Munu
函数并进入Start()
函数。 You also have to un-register to the Button
event in the OnDisable()
function. 您还必须在
OnDisable()
函数中取消注册Button
事件。
Below is what your code should look like: 以下是您的代码应如下所示:
Button button;
void Start()
{
button = GameObject.Find("Btn").GetComponent<Button>();
button.onClick.AddListener(Menu);
}
void OnDisable()
{
button.onClick.RemoveListener(Menu);
}
void Menu()
{
///Put Your Button click code here
}
我解决我的问题与改变GameObject.Find("")
以Active.transform.Find("")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.