Files

77 lines
2.4 KiB
C#
Raw Permalink 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.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; // 目标数字
/// <summary>
/// 开始显示数字动画。
/// </summary>
/// <param name="animationTime">动画持续总时间。</param>
/// <param name="number">最终要显示的数字。</param>
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);
}
/// <summary>
/// 每帧更新UI显示逻辑。
/// </summary>
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更新队列中移除自身
}
}
/// <summary>
/// 立即显示目标数字,并停止任何正在进行的动画。
/// </summary>
public void ShowImmediately()
{
Clock.RemoveTickUI(this); // 如果正在TickUI中更新则停止它
text.text = target.ToString(); // 直接设置最终值
timer = time; // 为了内部状态一致性
}
private void OnDestroy()
{
// 确保组件销毁时从Clock中移除防止内存泄漏或对已销毁对象的访问
Clock.RemoveTickUI(this);
}
}
}