ButtonState.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using UnityEngine.EventSystems;
  4. namespace Rokid.UXR.Interaction {
  5. public class ButtonState : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerEnterHandler, IPointerExitHandler
  6. {
  7. [SerializeField]
  8. private Sprite pressed;
  9. [SerializeField]
  10. private Sprite highlight;
  11. [SerializeField]
  12. private Sprite normal;
  13. [SerializeField]
  14. private Image targetGraphic;
  15. [SerializeField]
  16. private Image hotArea;
  17. [SerializeField]
  18. private bool hovering;
  19. [SerializeField]
  20. private bool pointerDown;
  21. /// <summary>
  22. /// 默认 graphicScale
  23. /// </summary>
  24. private Vector3 oriGraphicScale;
  25. private Vector3 oriHotAreaScale;
  26. /// <summary>
  27. /// hover状态 graphicScale
  28. /// </summary>
  29. public float hoverScale = 1.0f;
  30. /// <summary>
  31. /// hover状态 hotArea
  32. /// </summary>
  33. public float hotAreaHoverScale = 1.0f;
  34. public float downScale = 1.0f;
  35. public void OnPointerDown(PointerEventData eventData)
  36. {
  37. pointerDown = true;
  38. }
  39. public void OnPointerUp(PointerEventData eventData)
  40. {
  41. pointerDown = false;
  42. }
  43. public void OnPointerEnter(PointerEventData eventData)
  44. {
  45. hovering = true;
  46. }
  47. public void OnPointerExit(PointerEventData eventData)
  48. {
  49. hovering = false;
  50. pointerDown = false;
  51. }
  52. private void Start()
  53. {
  54. oriGraphicScale = targetGraphic.transform.localScale;
  55. if (hotArea != null)
  56. oriHotAreaScale = hotArea.transform.localScale;
  57. }
  58. private void OnEnable()
  59. {
  60. OnPointerExit(null);
  61. }
  62. private void OnDisable()
  63. {
  64. OnPointerExit(null);
  65. }
  66. private void Update()
  67. {
  68. if (hovering && !pointerDown)
  69. {
  70. targetGraphic.sprite = highlight;
  71. targetGraphic.transform.localScale = oriGraphicScale * hoverScale;
  72. if (hotArea != null)
  73. hotArea.transform.localScale = oriHotAreaScale * hotAreaHoverScale;
  74. }
  75. else if (pointerDown)
  76. {
  77. targetGraphic.sprite = pressed;
  78. targetGraphic.transform.localScale = oriGraphicScale * downScale;
  79. if (hotArea != null)
  80. hotArea.transform.localScale = oriHotAreaScale * hotAreaHoverScale;
  81. }
  82. else
  83. {
  84. targetGraphic.sprite = normal;
  85. targetGraphic.transform.localScale = oriGraphicScale;
  86. if (hotArea != null)
  87. hotArea.transform.localScale = oriHotAreaScale;
  88. }
  89. }
  90. }
  91. }