using System.Globalization;
using Base;
using TMPro;
using UnityEngine;
namespace UI
{
public class SettlementUIText : MonoBehaviour, ITickUI
{
public TMP_Text text; // 文本组件,需在Inspector中赋值
private float time; // 动画总时长
private float timer; // 动画计时器
private int target; // 目标数字
///
/// 开始显示数字动画。
///
/// 动画持续总时间。
/// 最终要显示的数字。
public void StartShow(float animationTime, int number)
{
time = animationTime;
timer = 0;
target = number;
// 如果动画时间无效,则立即显示
if (time <= 0f)
{
Debug.LogWarning($"SettlementUIText: 动画时间为零或负数 ({time})。立即显示目标数字 {target}。");
ShowImmediately();
return;
}
Clock.AddTickUI(this);
}
///
/// 每帧更新UI显示逻辑。
///
public void TickUI()
{
timer += Time.deltaTime;
if (timer < time)
{
// 使用插值计算当前显示的数字,并转换为字符串
var easedValue = target * (timer / time);
text.text = Mathf.RoundToInt(easedValue).ToString(CultureInfo.InvariantCulture);
}
else // timer >= time
{
// 动画结束,显示最终目标数字
text.text = target.ToString();
Clock.RemoveTickUI(this); // 从全局UI更新队列中移除自身
}
}
///
/// 立即显示目标数字,并停止任何正在进行的动画。
///
public void ShowImmediately()
{
Clock.RemoveTickUI(this); // 如果正在TickUI中更新,则停止它
text.text = target.ToString(); // 直接设置最终值
timer = time; // 为了内部状态一致性
}
private void OnDestroy()
{
// 确保组件销毁时从Clock中移除,防止内存泄漏或对已销毁对象的访问
Clock.RemoveTickUI(this);
}
}
}