unity中的双击按钮检测和长按按钮的检测

unity中的双击按钮检测和长按按钮的检测

前言

今天使用UGUI的知识来实现一下 按钮的双击和按钮长按的检测

其实我们的思路就是 每次按下检测按下时间 如果长按时间超过某一特定的值
那么我们判定 长按

至于双击的检测 我们是 当第一次按下之后抬起 开始计时 在特定值 之前 我们如果检测到按下第二次
我们判定双击按钮

using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
public class ButtonExtension : MonoBehaviour, IPointerClickHandler, IPointerDownHandler, IPointerUpHandler, IPointerExitHandler
    public float pressDurationTime = 1;
    public bool responseOnceByPress = false;
    public float doubleClickIntervalTime = 0.5f;
    public UnityEvent onDoubleClick;
    public UnityEvent onPress;
    public UnityEvent onClick;
    private bool isDown = false;
    private bool isPress = false;
    private float downTime = 0;
    private float clickIntervalTime = 0;
    private int clickTimes = 0;
    void Update()
        if (isDown)
            if (responseOnceByPress && isPress)
                return;
            downTime += Time.deltaTime;
            if (downTime > pressDurationTime)
                isPress = true;
                onPress.Invoke();
        if (clickTimes >= 1)
            clickIntervalTime += Time.deltaTime;
            if (clickIntervalTime >= doubleClickIntervalTime)
                if (clickTimes >= 2)
                    onDoubleClick.Invoke();
                    onClick.Invoke();
                clickTimes = 0;
                clickIntervalTime = 0;
    public void OnPointerDown(PointerEventData eventData)//鼠标按下
        isDown = true;
        downTime = 0;
    public void OnPointerUp(PointerEventData eventData)//鼠标抬起
        isDown = false;
    public void OnPointerExit(PointerEventData eventData)//指针出去
        isDown = false;
        isPress = false;
    public void OnPointerClick(PointerEventData eventData)//按键按下时调用
        if (!isPress)
            //onClick.Invoke();
            clickTimes += 1;
            isPress = false;
}

上边是按钮的类 之后我们还要一个触发的脚本

using UnityEngine;
public class Test : MonoBehaviour
    ButtonExtension btn;
    void Start()
        btn = GetComponent<ButtonExtension>();
        btn.onClick.AddListener(Click);
        btn.onPress.AddListener(Press);
        btn.onDoubleClick.AddListener(DoubleClick);
    void Click()
        Debug.Log("单击");
    void Press()
        Debug.Log("按压");