2026-04-01 19:15:20 +08:00

105 lines
2.6 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 System.Collections;
using UnityEngine;
using UnityEngine.UI;
using ZXKFramework;
namespace YiLiao.XinFeiTingZhen
{
public class CountdownPanel : UIBase
{
[Tooltip("倒计时总时长(秒)")]
public float duration = 20f;
[Tooltip("绑定带有Filled属性的Image组件")]
public Image countdownImage;
[Tooltip("绑定显示时间的Text组件")]
public Text timeText;
// 用于存储协程引用,以便随时停止
private Coroutine countdownCoroutine;
public Action callBack;
public override string GroupName => "CountdownPanel";
public override string Name => "CountdownPanel";
/// <summary>
/// 启动倒计时
/// </summary>
public void StartCountdown(Action callBack)
{
this.callBack = callBack;
// 如果已经有倒计时在运行,先停止旧的
if (countdownCoroutine != null)
{
StopCoroutine(countdownCoroutine);
}
// 启动新的协程
countdownCoroutine = StartCoroutine(CountdownRoutine());
}
/// <summary>
/// 关闭/停止倒计时
/// </summary>
public void StopCountdown()
{
if (countdownCoroutine != null)
{
StopCoroutine(countdownCoroutine);
countdownCoroutine = null;
}
Debug.Log("倒计时已关闭");
}
/// <summary>
/// 倒计时协程
/// </summary>
private IEnumerator CountdownRoutine()
{
float elapsedTime = 0f;
// 循环直到时间耗尽
while (elapsedTime < duration)
{
// 计算剩余时间
float remainingTime = duration - elapsedTime;
// 更新UI
UpdateTimerUI(remainingTime);
// 累加时间
elapsedTime += Time.deltaTime;
// 等待一帧
yield return null;
}
// 倒计时结束确保显示为0
UpdateTimerUI(0);
Debug.Log("倒计时结束!");
callBack?.Invoke();
// 协程结束,清空引用
countdownCoroutine = null;
}
void UpdateTimerUI(float time = 0)
{
// 防止除以0或负数导致的UI错误
float fill = duration > 0 ? time / duration : 0;
countdownImage.fillAmount = fill;
int seconds = Mathf.CeilToInt(time);
timeText.text = seconds.ToString() + "s";
}
public override void Hide()
{
base.Hide();
StopCountdown();
}
}
}