Customizing your buttons with code in Unity
Unity has an easy to use built-in Button interface in the Canvas UI. But with many easy to use things, they come with limitations. For instance, if we wanted a method to run when a button is highlighted, we wouldn’t be able to do this unless it is written in some type of code.
In my example, I want an icon to appear next to a button when the user highlights it. We can use the UnityEngine.EventSystems to make the changes we need.
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class Button : MonoBehaviour, ISelectHandler, IPointerEnterHandler, IPointerExitHandler, IDeselectHandler
We can derive our class from the above parent classes and then use the following methods:
// When highlighted with mouse.
public void OnPointerEnter(PointerEventData eventData)
{
// Do something.
}
// When no longer highlighted with mouse.
public void OnPointerExit(PointerEventData eventData)
{
// Do something.
}
// When selected.
public void OnSelect(BaseEventData eventData)
{
// Do something.
}
//when deselected
public void OnDeselect(BaseEventData eventData)
{
// Do something.
}
There are other useful methods we can use with our buttons located within the Unity API here.