The new Unity 4.6 System comes with an EventTrigger System. From the editor this is easy to use but how does one add a trigger, for example for PointerClick, by script (C#) ?
Let’s say i have a function called Foo() in a class called ExampleAction on the a child of the gameObject that contains the event trigger. How do i assign now a PointerClick to call ExampleAction.Foo() on that childobject
I’ve made an extension method for it. Simply include this class somewhere in your project:
using UnityEngine.EventSystems;
public static class ExtensionMethods
{
public static void AddListener (this EventTrigger trigger, EventTriggerType eventType, System.Action<PointerEventData> listener)
{
EventTrigger.Entry entry = new EventTrigger.Entry();
entry.eventID = eventType;
entry.callback.AddListener(data => listener.Invoke((PointerEventData)data));
trigger.triggers.Add(entry);
}
}
Then use it like this:
using UnityEngine;
using UnityEngine.EventSystems;
public class UIController : MonoBehaviour
{
void Start ()
{
EventTrigger myEventTrigger = GetComponent<EventTrigger> (); //you need to have an EventTrigger component attached this gameObject
myEventTrigger.AddListener (EventTriggerType.PointerClick, onClickListener);
}
void onClickListener (PointerEventData eventData)
{
//put your logic here...
}
}
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class ClickableButton : MonoBehaviour, IPointerClickHandler {
public void OnPointerClick(PointerEventData eventData)
{
if (eventData.button == PointerEventData.InputButton.Left)
Debug.Log("Left click");
else if (eventData.button == PointerEventData.InputButton.Middle)
Debug.Log("Middle click");
else if (eventData.button == PointerEventData.InputButton.Right)
Debug.Log("Right click");
}
}