LongPressMonitor.cs 964 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. using UnityEngine;
  2. using UnityEngine.EventSystems;
  3. using System;
  4. public class LongPressMonitor : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerExitHandler
  5. {
  6. public Action onLongPress;
  7. public float interval = 1.0f;
  8. bool isDown;
  9. float downTime;
  10. [NonSerialized] public bool isLongPress; //最后一次点击是否为长按
  11. void Update()
  12. {
  13. if (isDown)
  14. {
  15. if (Time.time - downTime > interval)
  16. {
  17. isDown = false;
  18. isLongPress = true;
  19. onLongPress?.Invoke();
  20. }
  21. }
  22. }
  23. public void OnPointerDown(PointerEventData eventData)
  24. {
  25. isDown = true;
  26. isLongPress = false;
  27. downTime = Time.time;
  28. }
  29. public void OnPointerExit(PointerEventData eventData)
  30. {
  31. isDown = false;
  32. }
  33. public void OnPointerUp(PointerEventData eventData)
  34. {
  35. isDown = false;
  36. }
  37. }