Game Development Reference
In-Depth Information
Executing events
To use the built-in events (so your script reacts when the event occurs) is quite
simple. As an example, we'll put together a simple script that shows a tooltip when
you hover over a UI element.
First create a new
C#
script called
Tooltip
and replace its contents with the following:
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class Tooltip : MonoBehaviour
{
private bool m_tooltipDisplayed = false;
public RectTransform TooltipItem;
private Vector3 m_tooltipOffset;
}
Next we'll add the two event interfaces we will use for the tooltip,
IPointerEnterHandler
(to detect when the mouse moves over a UI GameObject)
and
IPointerExitHandler
(to detect when the mouse moves away from a UI
GameObject). To do this, simply update the class definition to the following:
public class Tooltip : MonoBehaviour
, IPointerEnterHandler,
IPointerExitHandler
When you create your own classes using the event handlers, the
interface names are sometimes shown with red squiggles. To fix this just
right-click the interface with the red squiggle and select
Resolve | using
UnityEngine.EventSystems
menu item.
You can also just add the
using UnityEngine.EventSystems;
to the
top of the script manually.
With the interfaces added, we need to add the handler methods for those interfaces,
so add the following to your script:
public void OnPointerEnter(PointerEventData eventData)
{
//Mark the tooltip as displayed
m_tooltipDisplayed = true;
//Move the tooltip item to the detected GO and offset it above
TooltipItem.transform.position =