| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- using System;
- using DG.Tweening;
- using UnityEngine;
- using UnityEngine.UI;
- namespace AppUI.Util.Switch
- {
- [RequireComponent(typeof(Button))]
- public class UISwitchToggle : MonoBehaviour
- {
- [Header("UI")]
- [SerializeField] Image background;
- [SerializeField] RectTransform knob;
- [Header("Color")]
- [SerializeField]
- Color onColor =
- new Color(0.3f, 0.85f, 0.4f);
- [SerializeField]
- Color offColor =
- new Color(0.7f, 0.7f, 0.7f);
- [Header("Move")]
- [SerializeField] float knobOnX = 30f;
- [SerializeField] float knobOffX = -30f;
- [SerializeField] float duration = 0.2f;
- bool isOn;
- Action<bool> onValueChanged;
- Button btn;
- void Awake()
- {
- btn = GetComponent<Button>();
- btn.onClick.RemoveListener(OnClick);
- btn.onClick.AddListener(OnClick);
- }
- public void Init(
- bool defaultValue,
- Action<bool> callback)
- {
- isOn = defaultValue;
- onValueChanged = callback;
- Refresh(false);
- }
- void OnClick()
- {
- AudioMgr.ins.PlayBtn();
- isOn = !isOn;
- Refresh(true);
- onValueChanged?.Invoke(isOn);
- }
- public void SetValue(bool value)
- {
- isOn = value;
- Refresh(false);
- }
- public bool GetValue()
- {
- return isOn;
- }
- void Refresh(bool animate)
- {
- // background
- background.color =
- isOn
- ? onColor
- : offColor;
- // knob position
- //knob.GetComponent<Image>().color =
- // isOn
- // ? offColor
- // : onColor;
- float targetX =
- isOn
- ? knobOnX
- : knobOffX;
- if (animate)
- {
- knob.DOAnchorPosX(targetX, duration)
- .SetEase(Ease.OutCubic);
- }
- else
- {
- Vector2 pos = knob.anchoredPosition;
- pos.x = targetX;
- knob.anchoredPosition = pos;
- }
- }
- }
- }
|