Try putting the button into a separate variable. Initialize it at startup. And there to add a listener.
And when the object is destroyed, do not forget the listener to remove RemoveListener
using UnityEngine; using System.Collections; using UnityEngine.UI; public class Trashscript : MonoBehaviour { public GameObject Temp; private GameObject Active; int Counter; private Button myselfButton; void Start() { myselfButton = GameObject.Find("Btn").GetComponent<Button>(); myselfButton.onClick.AddListener(Menu); Menu(); } void Menu() { Counter++; if (Active != null) Destroy(Active); Active = Instantiate(Temp); GameObject.Find("Text").GetComponent<Text>().text = Counter.ToString(); } void Destroy() { myselfButton.onClick.RemoveListener(Menu); } }
UPD
If initially there are no Canvas on the scene and if the GameObject Temp
is just the same as the canvas
prefab is instantiated and instantiated into Active
, then the error is trivial: instead of searching on the GameObject.Find(....
scene GameObject.Find(....
just apply the actions to the instantiated an object that lies in a variable, i.e.
Active.GetComponentInChildren.....
In general, the code will be as follows:
public GameObject Temp; private GameObject Active; int Counter; void Start() { Menu(); } void Menu() { Counter++; if (Active != null) { Destroy(Active); Active = null; } Active = Instantiate(Temp); Active.GetComponentInChildren<Text>().text = Counter.ToString(); Active.GetComponentInChildren<Button>().onClick.AddListener(this.Menu); }
By the way, I also added Active = null;
because with Destroy(Active);
the object will be destroyed from the scene, but it will still remain in the Active
field.
Comment!
If the generated canvas has a lot of buttons, and not one, then there is another option:
If the layout of the buttons does not change, you can use GetChild (index) to get a specific item. Something like
Active.transform.GetChild(1).GetComponent<Button>().onClick.AddListener(Menu);
either specify specific names for these specific buttons and simply find via the Find
directly the Active
object. I.e:
Active.transform.Find("MyButtonName").GetComponent<Button>().onClick.AddListener(Menu);