Unity3D 实现 UI 元素双击和长按功能。
UI 双击和长按
上一篇文章实现了拖拽接口,这篇文章来实现 UI 的双击和长按。
双击
创建脚本 UIDoubleClick.cs
,创建一个 Image,并把脚本挂载到它身上。
在脚本中,继承 IPointerClickHandler
接口,实现 OnPointerClick
点击方法。
第一次点击时,记录点击的时间,如果第二次点击的时间,和上次点击时间的间隔非常短,则判定为双击。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
| using UnityEngine; using UnityEngine.EventSystems;
public class UIDoubleClick : MonoBehaviour, IPointerClickHandler { public float doubleClickThreshold = 0.2f; float lastClickTime = 0f;
public void OnPointerClick(PointerEventData eventData) { float currentTime = Time.time;
if (currentTime - lastClickTime < doubleClickThreshold) { OnDoubleClick(); }
lastClickTime = currentTime; }
void OnDoubleClick() { Debug.Log("双击"); } }
|
运行效果:

长按
创建脚本 UILongPress.cs
,并挂载到 Image 身上。
在脚本中,继承 IPointerDownHandler
和 IPointerUpHandler
接口,实现 OnPointerDown
(按下)和 OnPointerUp
(抬起)方法。
按下时,记录按下的时间和按住的状态,在 Update
中检查长按的时间和状态,达到长按的时间阈值后,执行一次长按的逻辑,并把长按状态重置。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| using UnityEngine; using UnityEngine.EventSystems;
public class UILongPress : MonoBehaviour, IPointerDownHandler, IPointerUpHandler { public float longPressThreshold = 1.0f; float pressStartTime; bool isPressing = false;
public void OnPointerDown(PointerEventData eventData) { isPressing = true; pressStartTime = Time.time; }
public void OnPointerUp(PointerEventData eventData) { isPressing = false; }
void Update() { if (isPressing && (Time.time - pressStartTime) > longPressThreshold) { OnLongPress(); isPressing = false; } }
void OnLongPress() { Debug.Log("长按"); } }
|
运行效果:
