美文网首页
11、按钮扩展:单击、双击、长按

11、按钮扩展:单击、双击、长按

作者: GameObjectLgy | 来源:发表于2020-11-03 14:47 被阅读0次
using UnityEngine;  
using UnityEngine.UI;  
using UnityEngine.EventSystems;  
  
public class MJCard : MonoBehaviour,IPointerClickHandler {  
  
    float lastClickTime;  //不要申明在方法内
 
    public void OnPointerClick(PointerEventData eventData)  
    {    
        if (Time.time - lastClickTime < 0.2)  
        {  
            Debug.log("双击");  
        }  
       lastClickTime = Time.time;  
    }

同理,同做一个按钮的拓展,实现单击,双击,长按功能

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();
                }
                else
                {
                    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;
        }
        else
            isPress = false;
    }
}
1.png

相关文章

网友评论

      本文标题:11、按钮扩展:单击、双击、长按

      本文链接:https://www.haomeiwen.com/subject/qthtuktx.html