_xiaofang/xiaofang/Assets/Script/UI/SkillCoolDownUI.cs

58 lines
1.4 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System;
using System.Threading.Tasks;
public class SkillCoolDownUI : MonoBehaviour
{
public Image cooldownImage; // 拖动Image组件到这里
public Text cooldowntext;//显示计时器剩余时间
public event Action OnCooldownFinished; // 冷却结束事件
private Coroutine countdownCoroutine;
public async void StartCooldown(float cooldownTime)
{
if (countdownCoroutine != null)
{
StopCoroutine(countdownCoroutine);
}
// 调用异步方法来启动冷却
await CooldownRoutine(cooldownTime);
}
public async Task CooldownRoutine(float cooldownTime)
{
float elapsed = 0f;
cooldownImage.fillAmount = 1; // 设置为满
while (elapsed < cooldownTime)
{
elapsed += Time.deltaTime;
cooldownImage.fillAmount = 1 - (elapsed / cooldownTime);
cooldowntext.text = ((1 - (elapsed / cooldownTime)) * 10).ToString("F1");
// 使用 Task.Delay 来代替协程的 yield return
await Task.Yield(); // 让出当前帧,等待下次更新
}
HandleCooldownFinished();
}
private void HandleCooldownFinished()
{
cooldownImage.fillAmount = 0; // 重新设置为0
OnCooldownFinished?.Invoke(); // 触发冷却结束事件
Destroy(gameObject);
}
}