TH1/Unity/Assets/Scripts/UI/Common/ToggleButtonController.cs
2025-07-24 16:21:26 +08:00

84 lines
2.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using Animancer;
using TH1Resource;
using TMPro;
using UnityEngine;
using UnityEngine.UI; // 用于 Button 组件
// 自动为该物体添加一个 Button 组件,确保它总是可点击的
[RequireComponent(typeof(Button))]
public class ToggleButtonController : MonoBehaviour
{
private bool _isOn; // 当前开关状态
//操作对象
public GameObject Handle;
public AnimationClip TurnOn;
public AnimationClip TurnOff;
private AnimancerComponent _anim;
public Action On;
public Action Off;
void Start()
{
// 1. 加载状态
// PlayerPrefs.GetInt(key, defaultValue) 如果找不到key则返回1(ON)
_isOn = true;
// 2. 初始化UI状态 (无动画)
// 直接将动画播放到最后一帧,瞬间完成状态切换
_anim = Handle.transform.GetComponent<AnimancerComponent>();
if (_anim != null)
{
//var state = _anim.Play(_isOn ? TurnOn : TurnOff);
var state = _anim.Play(TurnOn);
state.NormalizedTime = 1f;
}
// 3. 监听点击事件
GetComponent<Button>().onClick.AddListener(OnToggleClicked);
}
public void Refresh(bool isON,Action actOn,Action actOff)
{
_isOn = isON;
On = actOn;
Off = actOff;
if (_anim != null)
{
//var state = _anim.Play(_isOn ? TurnOn : TurnOff);
var state = _anim.Play(TurnOn);
state.NormalizedTime = 1f;
}
}
/// <summary>
/// 当Toggle被点击时调用
/// </summary>
private void OnToggleClicked()
{
// 1. 翻转状态
_isOn = !_isOn;
if (_isOn)
On.Invoke();
else
Off.Invoke();
//2. 播放对应动画
if(_anim != null)
_anim.Play(_isOn ? TurnOn : TurnOff );
// 3. 传递信息
}
void OnDestroy()
{
// 移除监听,防止内存泄漏
var button = GetComponent<Button>();
if (button != null)
{
button.onClick.RemoveListener(OnToggleClicked);
}
}
}