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!

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Advertisements

Force Unity to scroll to the bottom of a scroll rect

So, I’ve got a textbox (TextMeshPro) with a load of text in it. As the game progresses, I add more text to the textbox and I want the user to see the bottom of the text (the last bit added)…

/// <summary>
/// Add text to the panel at the bottom of the screen
/// </summary>
public void AddTextToBottomPanel(string a_text)
{
  m_bottomPanelText.text += a_text;
  StartCoroutine(PushToBottom());
}

IEnumerator PushToBottom()
{
  yield return new WaitForEndOfFrame();
  m_bottomScrollRect.verticalNormalizedPosition = 0;
  LayoutRebuilder.ForceRebuildLayoutImmediate((RectTransform)m_bottomScrollRect.transform);
}