Handling long press events in uGUI (Unity 4.6)

I’ve been playing with the new uGUI system that was introduced in Unity v4.6 and I’ve gotta say, I love it. I’ve been a fan of NGUI as my go-to UI solution for years now and wasn’t going to switch without good reason. Well, I found plenty of reasons… and I plan to retire NGUI in favor of uGUI moving forward.

I’ve been doing a total overhaul of the Kiduoso UI using the new uGUI system. As I’ve been working I’ve found that, even for something as UI heavy as Kiduoso, uGUI handles most everything I need out of the box. There have been a few exceptions, of course. One of them is handling the long press.

The long press (sometimes called long click, long tap, or press and hold) is the de facto standard replacement for right-clicking in the world of mobile development. You press on something for a long period of time (a second or two  usually) and then you’re provided with a context menu based on what you were pressing on.

How to do this in uGUI isn’t obvious, but luckily, it’s pretty straightforward. Here’s the C# code for a LongPressEventTrigger component:

using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using System.Collections;

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.0f;

	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;
	}
}

All you need to do is add the LongPressEventTrigger component to  your UI object that you want to long press. Then, the onLongPress event will fire after pressing for the duration you specify.

This component can exist side-by-side with a Button component as well. So you can support long press as well as regular press.

Comments

comments