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;
SetCurTimeZero();
}
public float EndCountDown()
{
EndTime = CurTime;
startT = false;
return CurTime;
}
public void RefreshTime() {
text.text = StringFormat(0);
}
public void CloseCountDown() {
startT = false;
RefreshTime();
}
void SetCurTimeZero()
{
CurTime = 0;
}
public void Update()
{
if (!startT) return;
CurTime = Time.time - startTime;
if (CurTime >= TotleTime)
{
CurTime = TotleTime;
Debug.Log("时间到");
startT = false;
if (onTimeCountDown != null)
onTimeCountDown.Invoke();
}
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;
}
public int getLeftTime()
{
return (int)(TotleTime - CurTime);
}
}
StartCountDown : 开始倒计时,参数为倒计时时间
GetCurTime : 获取已用时间
getLeftTime : 返回剩余时间
FR:海涛高软(Hunk Xu)
QQ技术交流群:386476712