With the new uGUI in Unity 4.6, you can easily add events to controls by adding an EventTrigger script. But it does not include the long press event, you need to implement the long press event.
Long press event
Here’s one way to do it, from Handling Long Press Events in uGUI (Unity 4.6)
using UnityEngine; using UnityEngine.Events; using UnityEngine.EventSystems; public class LongPressEventTrigger : UIBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerExitHandler { [Tooltip("How long must pointer be down on this object to trigger a long press")] public float DurationThreshold = 1.0 f; public UnityEvent onLongPress = new UnityEvent(); private bool isPointerDown = false; private bool longPressTriggered = false; private float timePressStarted; private void Update() { if (isPointerDown && ! longPressTriggered) { if (Time.time - timePressStarted > durationThreshold) { longPressTriggered = true; onLongPress.Invoke(); } } } public void OnPointerDown(PointerEventData eventData) { timePressStarted = Time.time; isPointerDown = true; longPressTriggered = false; } public void OnPointerUp(PointerEventData eventData) { isPointerDown = false; } public void OnPointerExit(PointerEventData eventData) { isPointerDown = false; }}Copy the code
Long press or click events
If there is a long press event and a click event, then we need to determine whether the long press event has been executed. If the long press event has been executed, the click event cannot be executed. The code is as follows:
using UnityEngine; using UnityEngine.Events; using UnityEngine.EventSystems; public class LongPressOrClickEventTrigger : UIBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerExitHandler, IPointerClickHandler { [Tooltip("How long must pointer be down on this object to trigger a long press")] public float DurationThreshold = 1.0 f; public UnityEvent onLongPress = new UnityEvent(); public UnityEvent onClick = new UnityEvent(); private bool isPointerDown = false; private bool longPressTriggered = false; private float timePressStarted; private void Update() { if (isPointerDown && ! longPressTriggered) { if (Time.time - timePressStarted > durationThreshold) { longPressTriggered = true; onLongPress.Invoke(); } } } public void OnPointerDown(PointerEventData eventData) { timePressStarted = Time.time; isPointerDown = true; longPressTriggered = false; } public void OnPointerUp(PointerEventData eventData) { isPointerDown = false; } public void OnPointerExit(PointerEventData eventData) { isPointerDown = false; } public void OnPointerClick(PointerEventData eventData) { if (! longPressTriggered) { onClick.Invoke(); }}}Copy the code