using System;
using UnityEngine;
///
/// 时间单位
///
public enum TimeUnit
{
MILLSECOND, //毫秒
SECOND, //秒
MINUTE, //分钟
HOUR, //小时
}
///
/// 定时器
///
public class Timer
{
///
/// 计时结束回调事件
///
public event Action OnEnd;
///
/// 计时更新事件
///
public event Action OnUpdate;
//定时时长
private float duration;
//开始计时时间
private float beginTime;
//已计时间
private float elapsedTime;
//缓存时间(用于暂停)
private float cacheTime;
//是否循环
private bool loop;
//是否暂停
private bool isPaused;
//是否计时完成
private bool isFinished;
///
/// 构造函数
///
/// 定时时长
/// 时间单位
/// 是否循环
public Timer(float duration, TimeUnit timeUnit = TimeUnit.SECOND, bool loop = false)
{
switch (timeUnit)
{
case TimeUnit.MILLSECOND: this.duration = duration / 1000; break;
case TimeUnit.SECOND: this.duration = duration; break;
case TimeUnit.MINUTE: this.duration = duration * 60; break;
case TimeUnit.HOUR: this.duration = duration * 3600; break;
}
this.loop = loop;
beginTime = Time.realtimeSinceStartup;
}
///
/// 更新定时器
///
public void Update()
{
if(!isFinished && !isPaused)
{
elapsedTime = Time.realtimeSinceStartup - beginTime;
OnUpdate?.Invoke(Mathf.Clamp(elapsedTime, 0, duration));
if(elapsedTime >= duration)
{
OnEnd?.Invoke();
if (loop)
{
beginTime = Time.realtimeSinceStartup;
}
else
{
isFinished = true;
}
}
}
}
///
/// 暂停定时器
///
public void Pause()
{
if (!isFinished)
{
isPaused = true;
cacheTime = Time.realtimeSinceStartup;
}
}
///
/// 恢复定时器
///
public void Unpause()
{
if(!isFinished && isPaused)
{
beginTime += Time.realtimeSinceStartup - cacheTime;
isPaused = false;
}
}
///
/// 停止定时器
///
public void Stop()
{
isFinished = true;
}
}
Example:
Timer timer;
private void Start()
{
timer = new Timer(3f);
timer.OnEnd += () => Debug.Log("计时结束 总计时长3秒");
timer.OnUpdate += v => Debug.Log($"计时中 已计时长{v}秒");
}
private void Update()
{
timer.Update();
}