using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using QFramework;
using UnityEngine.UI;
using System;
using TMPro;
public class TimeCountdown :MonoBehaviour
{
public UnityEngine.Events.UnityEvent onTimeCountDown;
public TextMeshProUGUI text;
public float TotleTime = 30;
float startTime;
float EndTime;
float CurTime;
bool startT;
public void SetTotleTime(float totleTime) {
TotleTime = totleTime;
text.text = StringFormat(0);
}
public void StartCountDown(float totleTime)
{
TotleTime = totleTime;
startTime = Time.time;
startT = true;
}
public float EndCountDown()
{
EndTime = CurTime;
EventCenter.Broadcast<float>(FrameEvent.TimeCountDown, EndTime);
startT = false;
return CurTime;
}
public void RefreshTime() {
text.text = StringFormat(0);
}
public void CloseCountDown() {
startT = false;
RefreshTime();
}
public void Update()
{
if (!startT) return;
CurTime = Time.time - startTime;
if (CurTime >= TotleTime)
{
CurTime = TotleTime;
Debug.Log("时间到");
EventCenter.Broadcast<float>(FrameEvent.TimeCountDown, CurTime);
if (onTimeCountDown != null)
onTimeCountDown.Invoke();
startT = false;
}
if (text != null)
{
if (CurTime<=0) CurTime = 0;
text.text = StringFormat(CurTime);
}
}
private string StringFormat(float time)
{
var temp = TotleTime - time;
var t = TempFormat(temp);
var m = Temp2Time((temp / 60));
var s = Temp2Time((temp % 60));
var str = string.Format("{0}:{1}", m, s);
return str;
}
private string Temp2Time(float time)
{
return time > 10 ? TempFormat((time)) : "0" + TempFormat((time));
}
private string TempFormat(float f)
{
var t = Mathf.FloorToInt(f);
return t.ToString();
}
public float GetCurTime()
{
return CurTime;
}
}
------------------------------------------------
上面是倒计时的另一种写法,我之前也写过一种倒计时,如下,供大家参考:
https://blog.csdn.net/qq_15267341/article/details/78436528