U3DC.COM | 优三帝研究院

Menu

实现UGUI按钮长按事件

UGUI 对按钮提供了 onClick事件侦听,但是没有长按事件。正常情况下,我们会通过Update的帧刷来实现计时,从而实现跟时间相关的逻辑,比如倒计时,比如长按时间。很明显,帧刷是比较耗时的方式,那有没有更好的方式呢?有的,那就是使用Invoke来实现,这样不需要每帧都引入Update计算。
Invoke 在一个固定的时间之后调用一个函数。我们将这个时间设置为 holdTime = 1f;单位为秒。当按键松开或者从按钮上移开时,调用CancelInvoke() 取消延时调用。

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
36
37
38
39
40
41
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
public class ButtonLongPress : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerExitHandler
{
    [SerializeField]
    [Tooltip("How long must pointer be down on this object to trigger a long press")]
    private float holdTime = 1f;
    // Remove all comment tags (except this one) to handle the onClick event!
    //private bool held = false;
    //public UnityEvent onClick = new UnityEvent();
    public UnityEvent onLongPress = new UnityEvent();
    public void OnPointerDown(PointerEventData eventData)
    {
        //held = false;
        Invoke("OnLongPress", holdTime);
    }
    public void OnPointerUp(PointerEventData eventData)
    {
        CancelInvoke("OnLongPress");
        //if (!held)
        //    onClick.Invoke();
    }
    public void OnPointerExit(PointerEventData eventData)
    {
        CancelInvoke("OnLongPress");
    }
    private void OnLongPress()
    {
        //held = true;
        onLongPress.Invoke();
    }
}

我们可以将这个脚本挂到Button上。

如果你希望在侦听长按时间的同时,也能侦听点击事件,就把上面脚本中注释掉的代码取消注释就可以了。

打赏
— 于 共写了1310个字
— 文内使用到的标签:

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据