Skip to content

Instantly share code, notes, and snippets.

@renaudbedard
Last active July 8, 2016 03:27
Show Gist options
  • Save renaudbedard/9f5a37495ce4988d5a3b9fb46e305a34 to your computer and use it in GitHub Desktop.
Save renaudbedard/9f5a37495ce4988d5a3b9fb46e305a34 to your computer and use it in GitHub Desktop.
Generic method to hook events to Unity 4.6+ UI EventTriggers
public static class EventExtensions
{
public static void AddEvent<TSource, TEvent>(this EventTrigger _trigger, EventTriggerType _eventType, TSource _source, Action<TSource, TEvent> _delegate)
where TEvent : BaseEventData
{
EventTrigger.TriggerEvent triggerEvent = new EventTrigger.TriggerEvent();
triggerEvent.AddListener(_data => _delegate(_source, _data as TEvent));
_trigger.triggers.Add(new EventTrigger.Entry { eventID = _eventType, callback = triggerEvent });
}
}
// sample usage :
// var eventTrigger = someImage.GetComponent<EventTrigger>();
// eventTrigger.AddEvent<Image, PointerEventData>(EventTriggerType.PointerEnter, someImage, OnImageEnter);
// ...
// void OnImageEnter(Image _source, PointerEventData _eventData)
// {
// ...
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment