So, when you add an event to a button using AddListener, the event doesn’t show up in the inspector so you can’t see what’s going to be triggered by the button. When looking at the button in Play mode you see something like this : –

Bad.PNG

Events need to show in the Inspector so you know what’s going on when you’re trying to figure out how code is being triggered. Below is a very simple example of how to do this:-

using UnityEditor.Events;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;

public class ButtonTest : MonoBehaviour
{
  public Button m_button;

  void Start()
  {
    // This will work and WILL show in the Inspector
    UnityAction<GameObject> action = new UnityAction<GameObject>(this.OnClickEvent);
    UnityEventTools.AddObjectPersistentListener<GameObject>(m_button.onClick, action, this.gameObject);
  }

  /// Handle the button click event
  public void OnClickEvent(GameObject a_gameObject)
  {
    Debug.Log("Button Pressed");
  }
}

…and the result is as follows…

Good.PNG

Hope it helps!

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Advertisements