using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using UnityEngine;
public class CountDownTool
{
static Timer timer = new Timer(TimerCallBack);
static Stopwatch stopwatch = new Stopwatch();
/// <summary>
/// 是否完成
/// </summary>
public static bool Complete { get; private set; }
/// <summary>
/// 时间限制
/// </summary>
static TimeSpan Restrict { get; set; }
/// <summary>
/// 倒计时时间
/// </summary>
public static TimeSpan CountDown
{
get
{
return Restrict - stopwatch.Elapsed;
}
}
/// <summary>
/// 开始计时
/// </summary>
/// <param name="_restrict">倒计时需要的时间</param>
public static void Start(TimeSpan _restrict)
{
Restrict = _restrict;
stopwatch.Start();
timer.Change(_restrict, Timeout.InfiniteTimeSpan);
Complete = false;
}
/// <summary>
/// 最后初始化
/// </summary>
public static void Reset()
{
stopwatch.Reset();
Complete = false;
timer.Change(Timeout.InfiniteTimeSpan, Timeout.InfiniteTimeSpan);
}
static void TimerCallBack(object obj)
{
Complete = true;
}
调用方式
private void Update()
{
timeTxt.text = "倒计时:" + $"{CountDownTool.CountDown.Minutes}:{CountDownTool.CountDown.Seconds}";
}
void Start()
{
CountDownTool.Start(new System.TimeSpan(0, 0, 5f)); //倒计时为5秒
}