Tomas
Tomas

Reputation: 55

Unity3d c#. onClick.AddListener() works once

There's a void in the script, which reloads Canvas. The Canvas contains the Button object. I attach the reload void with the script.

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". After clicking the "Btn" Canvas reloads, but there isn't any "Text", and "Btn" doesn't work (onClick event do nothing).

Help.

Upvotes: 1

Views: 3342

Answers (2)

Tomas
Tomas

Reputation: 55

I solved my problem with changing the GameObject.Find("") to Active.transform.Find("").

Upvotes: 1

Programmer
Programmer

Reputation: 125315

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.

You have to move GetComponent<Button>().onClick.AddListener(Menu) out of the Munu function and into the Start() function. You also have to un-register to the Button event in the OnDisable() function.

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

}

Upvotes: 2

Related Questions