BooleanToggleVisualsController.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. using UnityEngine;
  2. using UnityEngine.EventSystems;
  3. using UnityEngine.UI;
  4. namespace Unity.VRTemplate
  5. {
  6. /// <summary>
  7. /// Controls the visual states of a boolean toggle switch UI
  8. /// </summary>
  9. [RequireComponent(typeof(Toggle))]
  10. public class BooleanToggleVisualsController : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
  11. {
  12. const float k_TargetPositionX = 17f;
  13. #pragma warning disable 649
  14. [SerializeField, Tooltip("The boolean toggle knob.")]
  15. RectTransform m_Knob;
  16. [SerializeField, Tooltip("How much to translate the button imagery on the z on hover.")]
  17. float m_ZTranslation = 5f;
  18. #pragma warning restore 649
  19. Toggle m_Toggle;
  20. float m_InitialBackground;
  21. Coroutine m_ColorFade;
  22. Coroutine m_LocalMove;
  23. void Awake()
  24. {
  25. m_Toggle = gameObject.GetComponent<Toggle>();
  26. //Add listener for when the state of the Toggle changes, to take action
  27. m_Toggle.onValueChanged.AddListener(ToggleValueChanged);
  28. if (m_Knob != null)
  29. {
  30. m_InitialBackground = m_Knob.localPosition.z;
  31. }
  32. }
  33. void OnEnable()
  34. {
  35. ToggleValueChanged(m_Toggle.isOn);
  36. }
  37. /// <inheritdoc />
  38. void IPointerEnterHandler.OnPointerEnter(PointerEventData eventData)
  39. {
  40. PerformEntranceActions();
  41. }
  42. /// <inheritdoc />
  43. void IPointerExitHandler.OnPointerExit(PointerEventData eventData)
  44. {
  45. PerformExitActions();
  46. }
  47. void ToggleValueChanged(bool value)
  48. {
  49. if (value)
  50. {
  51. m_Knob.localPosition = new Vector3(k_TargetPositionX, m_Knob.localPosition.y, m_Knob.localPosition.z);
  52. }
  53. else
  54. {
  55. m_Knob.localPosition = new Vector3(-k_TargetPositionX, m_Knob.localPosition.y, m_Knob.localPosition.z);
  56. }
  57. }
  58. void PerformEntranceActions()
  59. {
  60. if (m_Knob != null)
  61. {
  62. var backgroundLocalPosition = m_Knob.localPosition;
  63. backgroundLocalPosition.z = m_InitialBackground - m_ZTranslation;
  64. m_Knob.localPosition = backgroundLocalPosition;
  65. }
  66. }
  67. void PerformExitActions()
  68. {
  69. if (m_Knob != null)
  70. {
  71. var backgroundLocalPosition = m_Knob.localPosition;
  72. backgroundLocalPosition.z = m_InitialBackground;
  73. m_Knob.localPosition = backgroundLocalPosition;
  74. m_Knob.localScale = Vector3.one;
  75. }
  76. }
  77. }
  78. }