QQ截图20210511170042.png
using System;
using UnityEngine.UI;
public class CountDownTimer
{
bool _timerIsRunning = false;
Text timeText;
DateTime daysLeft;
Action action;
public CountDownTimer(Text text,double day=0, double hour = 0, double min = 0, double sec = 0, Action ac = null)
{
daysLeft = DateTime.Now.AddDays(day).AddHours(hour).AddMinutes(min).AddSeconds(sec);
action = ac;
timeText = text;
}
public void TimerStart()
{
_timerIsRunning = true;
}
public void TimerStop()
{
_timerIsRunning = false;
}
public void Update()
{
if (_timerIsRunning)
{
DateTime startDate = DateTime.Now;
var ts = daysLeft - startDate;
if (ts < TimeSpan.Zero)
{
_timerIsRunning = false;
action?.Invoke();
return;
}
float days = ts.Days;
float hour = ts.Hours;
float minutes = ts.Minutes;
float seconds = ts.Seconds;
timeText.text = string.Format("{0}天{1:00}:{2:00}:{3:00}", days, hour, minutes, seconds);
}
}
}
var timer = new CountDownTimer(text, day, hour, min, sec);
timer.TimerStart();
网友评论