Search code examples
unity-game-engineunity3d-gui

Unity3D Programmatically Assign EventTrigger Handlers


In the new Unity3D UI (Unity > 4.6), I'm trying to create a simple script I can attach to a UI component (Image, Text, etc) that will allow me to wedge in a custom tooltip handler. So what I need is to capture a PointerEnter and PointerExit on my component. So far I'm doing the following with no success. I'm seeing the EVentTrigger component show up but can't get my delegates to fire to save my life.

Any ideas?

public class TooltipTrigger : MonoBehaviour {

  public string value;

  void Start() {

    EventTrigger et = this.gameObject.GetComponent<EventTrigger>();

    if (et == null)
      et = this.gameObject.AddComponent<EventTrigger>();

    EventTrigger.Entry entry;
    UnityAction<BaseEventData> call;

    entry = new EventTrigger.Entry();
    entry.eventID = EventTriggerType.PointerEnter;
    call = new UnityAction<BaseEventData>(pointerEnter);
    entry.callback = new EventTrigger.TriggerEvent();
    entry.callback.AddListener(call);
    et.delegates.Add(entry);

    entry = new EventTrigger.Entry();
    entry.eventID = EventTriggerType.PointerExit;
    call = new UnityAction<BaseEventData>(pointerExit);
    entry.callback = new EventTrigger.TriggerEvent();
    entry.callback.AddListener(call);
    et.delegates.Add(entry);
  }

  private void pointerEnter(BaseEventData eventData) {
    print("pointer enter");
  }
  private void pointerExit(BaseEventData eventData) {
    print("pointer exit");
  }

}

Also... the other method I can find when poking around the forums and documentations is to add event handlers via interface implementations such as:

public class TooltipTrigger : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler {

  public string value;

  public void OnPointerEnter(PointerEventData data) {
    Debug.Log("Enter!");
  }

  public void OnPointerExit(PointerEventData data) {
    Debug.Log("Exit!");
  }

}

Neither of these methods seems to be working for me.


Solution

  • Second method (implementation of IPointerEnterHandler and IPointerExitHandler interfaces) is what you're looking for. But to trigger OnPointerEnter and OnPointerExit methods your scene must contain GameObject named "EventSystem" with EventSystem-component (this GameObject created automatically when you add any UI-element to the scene, and if its not here - create it by yourself) and components for different input methods (such as StandaloneInputModule and TouchInputModule).

    Also Canvas (your button's root object with Canvas component) must have GraphicRaycaster component to be able to detect UI-elements by raycasting into them.

    I just tested code from your post and its works just fine.