Files
bansonic_beta_main/Assets/scripts/selectYourSongFirst/UI_SelectSong_AutoPlayToggle.cs
T

115 lines
3.4 KiB
C#

using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;
public class UI_SelectSong_AutoPlayToggle : MonoBehaviour
{
[Header("Wiring")]
[SerializeField] private Button button;
[SerializeField] private Toggle toggle;
[SerializeField] private Image buttonImage;
[SerializeField] private Text labelText; // Text (Legacy)
[Header("Tween")]
[SerializeField] private float tweenDuration = 0.25f;
[SerializeField] private Ease tweenEase = Ease.OutCubic;
private static readonly Color32 OnBg = new Color32(0x3A, 0x3A, 0x3A, 0xFF);
private static readonly Color32 OffBg = new Color32(0xFF, 0xFF, 0xFF, 0xFF);
private static readonly Color32 OnText = new Color32(0xFF, 0xFF, 0xFF, 0xFF);
private static readonly Color32 OffText = new Color32(0x3A, 0x3A, 0x3A, 0xFF);
private void Awake()
{
TryAutoWire();
}
private void OnEnable()
{
TryAutoWire();
if (button != null)
{
button.onClick.RemoveListener(OnClick);
button.onClick.AddListener(OnClick);
}
if (toggle != null)
{
toggle.onValueChanged.RemoveListener(OnToggleChanged);
toggle.onValueChanged.AddListener(OnToggleChanged);
// Keep UI state consistent with global setting.
toggle.SetIsOnWithoutNotify(GameConfig.autoPlayEnabled);
}
ApplyVisual(GameConfig.autoPlayEnabled, instant: true);
}
private void OnDisable()
{
if (button != null)
{
button.onClick.RemoveListener(OnClick);
}
if (toggle != null)
{
toggle.onValueChanged.RemoveListener(OnToggleChanged);
}
KillTweens();
}
public void TryAutoWire()
{
button = button != null ? button : GetComponent<Button>();
toggle = toggle != null ? toggle : GetComponent<Toggle>();
buttonImage = buttonImage != null ? buttonImage : GetComponent<Image>();
if (buttonImage == null && toggle != null && toggle.targetGraphic is Image tgImage)
{
buttonImage = tgImage;
}
labelText = labelText != null ? labelText : GetComponentInChildren<Text>(true);
}
private void OnClick()
{
bool next = !GameConfig.autoPlayEnabled;
GameConfig.SetAutoPlayEnabled(next);
if (toggle != null)
{
toggle.SetIsOnWithoutNotify(next);
}
ApplyVisual(next, instant: false);
}
private void OnToggleChanged(bool isOn)
{
GameConfig.SetAutoPlayEnabled(isOn);
ApplyVisual(isOn, instant: false);
}
private void ApplyVisual(bool enabled, bool instant)
{
Color targetBg = enabled ? OnBg : OffBg;
Color targetText = enabled ? OnText : OffText;
if (instant || !Application.isPlaying || tweenDuration <= 0f)
{
if (buttonImage != null) buttonImage.color = targetBg;
if (labelText != null) labelText.color = targetText;
return;
}
KillTweens();
if (buttonImage != null)
buttonImage.DOColor(targetBg, tweenDuration).SetEase(tweenEase);
if (labelText != null)
labelText.DOColor(targetText, tweenDuration).SetEase(tweenEase);
}
private void KillTweens()
{
if (buttonImage != null) buttonImage.DOKill();
if (labelText != null) labelText.DOKill();
}
}