MyButton.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using UnityEngine.EventSystems;
  4. /// <summary>
  5. /// 我的自定义Button,继承 Button
  6. /// </summary>
  7. public class MyButton : Button
  8. {
  9. // 构造函数
  10. protected MyButton()
  11. {
  12. my_onDoubleClick = new ButtonClickedEvent();
  13. my_onLongPress = new ButtonClickedEvent();
  14. }
  15. // 长按
  16. public ButtonClickedEvent my_onLongPress;
  17. public ButtonClickedEvent OnLongPress { get { return my_onLongPress; } set { my_onLongPress = value; } }
  18. // 双击
  19. public ButtonClickedEvent my_onDoubleClick;
  20. public ButtonClickedEvent OnDoubleClick { get { return my_onDoubleClick; } set { my_onDoubleClick = value; } }
  21. // 长按需要的变量参数
  22. private bool my_isStartPress = false;
  23. private float my_curPointDownTime = 0f;
  24. private float my_longPressTime = 0f;
  25. private bool my_longPressTrigger = false;
  26. void Update()
  27. {
  28. CheckIsLongPress();
  29. }
  30. #region 长按
  31. /// <summary>
  32. /// 处理长按
  33. /// </summary>
  34. void CheckIsLongPress()
  35. {
  36. if (my_isStartPress && !my_longPressTrigger)
  37. {
  38. if (Time.time > my_curPointDownTime + my_longPressTime)
  39. {
  40. // my_longPressTrigger = true; my_isStartPress = false;
  41. if (my_onLongPress != null)
  42. {
  43. my_onLongPress.Invoke();
  44. }
  45. }
  46. }
  47. }
  48. public override void OnPointerDown(PointerEventData eventData)
  49. {
  50. // 按下刷新當前時間
  51. base.OnPointerDown(eventData);
  52. my_curPointDownTime = Time.time;
  53. my_isStartPress = true;
  54. my_longPressTrigger = false;
  55. }
  56. public override void OnPointerUp(PointerEventData eventData)
  57. {
  58. // 指針擡起,結束開始長按
  59. base.OnPointerUp(eventData);
  60. my_isStartPress = false;
  61. }
  62. public override void OnPointerExit(PointerEventData eventData)
  63. {
  64. // 指針移出,結束開始長按,計時長按標志
  65. base.OnPointerExit(eventData);
  66. my_isStartPress = false;
  67. }
  68. #endregion#region 双击(单击)
  69. public override void OnPointerClick(PointerEventData eventData)
  70. {
  71. //(避免已經點擊進入長按后,擡起的情況)
  72. if (!my_longPressTrigger)
  73. {
  74. // 正常單擊
  75. if (eventData.clickCount == 2)
  76. {
  77. if (my_onDoubleClick != null)
  78. {
  79. my_onDoubleClick.Invoke();
  80. }
  81. }// 雙擊
  82. else if (eventData.clickCount == 1)
  83. {
  84. onClick.Invoke();
  85. }
  86. }
  87. }
  88. }