UISwitchToggle.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. using System;
  2. using DG.Tweening;
  3. using UnityEngine;
  4. using UnityEngine.UI;
  5. namespace AppUI.Util.Switch
  6. {
  7. [RequireComponent(typeof(Button))]
  8. public class UISwitchToggle : MonoBehaviour
  9. {
  10. [Header("UI")]
  11. [SerializeField] Image background;
  12. [SerializeField] RectTransform knob;
  13. [Header("Color")]
  14. [SerializeField]
  15. Color onColor =
  16. new Color(0.3f, 0.85f, 0.4f);
  17. [SerializeField]
  18. Color offColor =
  19. new Color(0.7f, 0.7f, 0.7f);
  20. [Header("Move")]
  21. [SerializeField] float knobOnX = 30f;
  22. [SerializeField] float knobOffX = -30f;
  23. [SerializeField] float duration = 0.2f;
  24. bool isOn;
  25. Action<bool> onValueChanged;
  26. Button btn;
  27. void Awake()
  28. {
  29. btn = GetComponent<Button>();
  30. btn.onClick.RemoveListener(OnClick);
  31. btn.onClick.AddListener(OnClick);
  32. }
  33. public void Init(
  34. bool defaultValue,
  35. Action<bool> callback)
  36. {
  37. isOn = defaultValue;
  38. onValueChanged = callback;
  39. Refresh(false);
  40. }
  41. void OnClick()
  42. {
  43. AudioMgr.ins.PlayBtn();
  44. isOn = !isOn;
  45. Refresh(true);
  46. onValueChanged?.Invoke(isOn);
  47. }
  48. public void SetValue(bool value)
  49. {
  50. isOn = value;
  51. Refresh(false);
  52. }
  53. public bool GetValue()
  54. {
  55. return isOn;
  56. }
  57. void Refresh(bool animate)
  58. {
  59. // background
  60. background.color =
  61. isOn
  62. ? onColor
  63. : offColor;
  64. // knob position
  65. //knob.GetComponent<Image>().color =
  66. // isOn
  67. // ? offColor
  68. // : onColor;
  69. float targetX =
  70. isOn
  71. ? knobOnX
  72. : knobOffX;
  73. if (animate)
  74. {
  75. knob.DOAnchorPosX(targetX, duration)
  76. .SetEase(Ease.OutCubic);
  77. }
  78. else
  79. {
  80. Vector2 pos = knob.anchoredPosition;
  81. pos.x = targetX;
  82. knob.anchoredPosition = pos;
  83. }
  84. }
  85. }
  86. }