ButtonExtension.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using UnityEngine;
  2. using UnityEngine.Events;
  3. using UnityEngine.EventSystems;
  4. public class ButtonExtension : MonoBehaviour, IPointerClickHandler, IPointerDownHandler, IPointerUpHandler, IPointerExitHandler
  5. {
  6. public float pressDurationTime = 1;
  7. public bool responseOnceByPress = false;
  8. public float doubleClickIntervalTime = 0.5f;
  9. public UnityEvent onDoubleClick;
  10. public UnityEvent onPress;
  11. public UnityEvent onClick;
  12. private bool isDown = false;
  13. private bool isPress = false;
  14. private float downTime = 0;
  15. private float clickIntervalTime = 0;
  16. private int clickTimes = 0;
  17. void Update()
  18. {
  19. if (isDown)
  20. {
  21. if (responseOnceByPress && isPress)
  22. {
  23. return;
  24. }
  25. downTime += Time.deltaTime;
  26. if (downTime > pressDurationTime)
  27. {
  28. isPress = true;
  29. onPress.Invoke();
  30. }
  31. }
  32. if (clickTimes >= 1)
  33. {
  34. clickIntervalTime += Time.deltaTime;
  35. if (clickIntervalTime >= doubleClickIntervalTime)
  36. {
  37. if (clickTimes >= 2)
  38. {
  39. onDoubleClick.Invoke();
  40. }
  41. else
  42. {
  43. onClick.Invoke();
  44. }
  45. clickTimes = 0;
  46. clickIntervalTime = 0;
  47. }
  48. }
  49. }
  50. public void OnPointerDown(PointerEventData eventData)
  51. {
  52. isDown = true;
  53. downTime = 0;
  54. }
  55. public void OnPointerUp(PointerEventData eventData)
  56. {
  57. isDown = false;
  58. }
  59. public void OnPointerExit(PointerEventData eventData)
  60. {
  61. isDown = false;
  62. isPress = false;
  63. }
  64. public void OnPointerClick(PointerEventData eventData)
  65. {
  66. if (!isPress)
  67. {
  68. onClick.Invoke();
  69. clickTimes += 1;
  70. }
  71. else
  72. isPress = false;
  73. }
  74. }