[code]csharpcode:
using System;
using System.Collections.Generic;
using UnityEngine;
public class Timer
{
/// <summary>
/// 延迟时间
/// </summary>
private float _delayTime;
/// <summary>
/// 已经过去的时间
/// </summary>
private float _elapsedTime;
/// <summary>
/// 延迟事件
/// </summary>
private Action _action;
/// <summary>
/// 是否循环
/// </summary>
private bool _repeat;
private bool _end;
public bool end { get { return _end; } }
public Timer(float delay, Action action, bool repeat = false)
{
_delayTime = delay;
_action = action;
_repeat = repeat;
}
/// <summary>
/// 更新
/// </summary>
/// <param name="dt">Time.deltaTime</param>
public void Update(float dt)
{
_elapsedTime += dt;
if (_elapsedTime >= _delayTime)
{
if (_repeat)
{
_elapsedTime = _elapsedTime - _delayTime;
_action();
}
else
{
_action();
_end = true;
}
}
}
}
/// <summary>
/// 计时器管理器
/// </summary>
public class TimerManager : Singleton<TimerManager>
{
private List<Timer> _timers = new List<Timer>();
/// <summary>
/// 延迟执行程序
/// </summary>
/// <param name="delay">延迟时间</param>
/// <param name="action">延迟事件</param>
/// <param name="repeat">是否循环</param>
public void Invoke(float delay,Action action,bool repeat = false)
{
_timers.Add(new Timer(delay, action, repeat));
}
/// <summary>
/// 更新
/// </summary>
/// <param name="dt"></param>
public void Update(float dt)
{
for (int i = 0; i < _timers.Count; i++)
{
Timer timer = _timers[i];
if (timer.end)
{
_timers.Remove(timer);
}
else
{
timer.Update(dt);
}
}
}
/// <summary>
/// 清除计时器容器
/// </summary>
public void Clear()
{
_timers.Clear();
}
}