[Unity UGUI]点击和长按组件

需求

游戏项目中卡片经常需要按钮/卡片的点击或者长按事件,这里提供一个好用的组件。

组件

using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;

namespace Mga
{
    public class LongPressOrClickEventTrigger : UIBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerExitHandler, IPointerClickHandler
    {
        public float durationThreshold = 1.0f;

        public UnityEvent onLongPress = new UnityEvent();
        public UnityEvent onClick = 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;
        }

        public void OnPointerClick(PointerEventData eventData)
        {
            if (!longPressTriggered)
            {
                onClick.Invoke();
            }
        }
    }
}

用法

var pressSrc = Obj_ClickButton.gameObject.AddComponent<LongPressOrClickEventTrigger>();
pressSrc.onLongPress.AddListener(delegate ()
{
    //长按方法
});
pressSrc.onClick.AddListener(delegate ()
{
    //点击方法
});

你可能感兴趣的:(UGUI,长按或者点击,ugui长按)