using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using UnityEngine.EventSystems; /******************************************************************************* *Create By CG *Function image双击还是单击响应 *******************************************************************************/ namespace CG.UTility { public class ButtonExtension : MonoBehaviour,IPointerEnterHandler, IPointerClickHandler, IPointerDownHandler, IPointerUpHandler, IPointerExitHandler { public float pressDurationTime = 1; public bool responseOnceByPress = false; public float doubleClickIntervalTime = 0.25f; /// /// 双击 /// public UnityEvent onDoubleClick = new UnityEvent(); /// /// 长按 /// public UnityEvent onPress = new UnityEvent(); /// /// 点击 /// public UnityEvent onClick = new UnityEvent(); /// /// 悬浮 /// public UnityEvent onCover = new UnityEvent(); /// /// 离开 /// public UnityEvent onExit = new UnityEvent(); 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; } } } void IPointerEnterHandler.OnPointerEnter(PointerEventData eventData) { onCover?.Invoke(); } void IPointerDownHandler.OnPointerDown(PointerEventData eventData)//鼠标按下 { isDown = true; downTime = 0; } void IPointerUpHandler.OnPointerUp(PointerEventData eventData)//鼠标抬起 { isDown = false; } void IPointerExitHandler.OnPointerExit(PointerEventData eventData)//指针出去 { isDown = false; isPress = false; onExit?.Invoke(); } void IPointerClickHandler.OnPointerClick(PointerEventData eventData)//按键按下时调用 { if (!isPress) { //onClick.Invoke(); clickTimes += 1; } else isPress = false; } } }