0
\$\begingroup\$

When making a game menu, how do I hook into "OnSelect"/"OnDeselect"/"OnHighlight"/etc with custom callbacks?

The Button MonoBehaviour doesn't seem to allow subscribing to those events. And extending the class doesn't seem to work either.

I've worked on projects that built their own button system to get around this, but that felt wrong.

\$\endgroup\$
1
  • \$\begingroup\$ Are you using the UnityEngine.UI system package, or UnityEngine.UIElements? If the former, have you implemented the corresponding interfaces like ISelectHandler? \$\endgroup\$ Commented Aug 4, 2024 at 18:02

1 Answer 1

0
\$\begingroup\$

If you are using the default unity UI, one way to do that is by implementing some interfaces that unity provides for those callbacks.

ISelectHandler: Called when an object is selected.

IDeselectHandler: Called when an object is deselected.

IPointerEnterHandler: Called when the pointer enters an object's area (highlight).

IPointerExitHandler: Called when the pointer exits an object's area.

using UnityEngine;
using UnityEngine.EventSystems;

public class MenuCallbacks : MonoBehaviour, ISelectHandler, IDeselectHandler
{
    // Called when the object is selected
    public void OnSelect(BaseEventData eventData)
    {
        Debug.Log("Selected: " + gameObject.name);
        // Custom callback logic
    }

    // Called when the object is deselected
    public void OnDeselect(BaseEventData eventData)
    {
        Debug.Log("Deselected: " + gameObject.name);
        // Custom callback logic
    }
}
\$\endgroup\$
2
  • \$\begingroup\$ Does that mean reimplementing all the functionality in the Button class? \$\endgroup\$ Commented Aug 5, 2024 at 20:03
  • \$\begingroup\$ It's not like you will be reimplementing the button class, you will be just capturing the callbacks you want and applying your custom logic to it. \$\endgroup\$ Commented Aug 9, 2024 at 15:04

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.