Unity: Make a programmatically generated button event show up in the Inspector

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!

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s