先贴出代码:
public class Timer
{
// 双缓冲,防止计时器回调时更改计时器队列
List<Schedule> mFront = new List<Schedule>();
List<Schedule> mBack = new List<Schedule>();
List<Schedule> mGarbrage = new List<Schedule>();
public static Timer Instance
{
get { return mSingleton; }
}
static readonly Timer mSingleton = new Timer();
public Schedule SetSchedule(float time, System.Action<Schedule> func)
{
Schedule sc = new Schedule(time, func);
mFront.Add(sc);
return sc;
}
public Schedule SetSchedule(float time, bool usingWorldTimeScale, System.Action<Schedule> func)
{
Schedule sc = new Schedule(time, usingWorldTimeScale, func);
mFront.Add(sc);
return sc;
}
public void RemoveSchedule(Schedule sc)
{
if (sc == null) return;
mFront.Remove(sc);
mBack.Remove(sc);
}
public void SetSchedule(Schedule sc)
{
if (mBack.Contains(sc))
{
return;
}
if (!mFront.Contains(sc))
{
mFront.Add(sc);
}
}
public void Update()
{
if (mFront.Count > 0)
{
mBack.AddRange(mFront);
mFront.Clear();
}
float dt = Time.deltaTime;
for (int i = 0; i < mBack.Count; i++)
{
if (mBack[i].Canceled)
{
mGarbrage.Add(mBack[i]);
continue;
}
Schedule sc = mBack[i];
float tmpTime = sc.Time;
// TODO: if game is pause,InGameTimeScale value is 0.0f;
float InGameTimeScale = 1.0f;
tmpTime -= sc.UsingWorldTimeScale ? (dt * InGameTimeScale) : dt;
//tmpTime -= dt;
sc.ResetTime(tmpTime);
if (tmpTime <= 0)
{
if (sc.Callback != null)
{
sc.Callback(sc);
}
if (sc.Time <= 0)
{
mGarbrage.Add(sc);
}
}
}
for (int i = 0; i < mGarbrage.Count; i++)
{
if (mBack.Contains(mGarbrage[i]))
{
mBack.Remove(mGarbrage[i]);
}
}
mGarbrage.Clear();
}
}
public class Schedule
{
float mTime = 0.0001f;
System.Action<Schedule> mDelegate;
bool mCanceled = false;
bool mUseWorldTimeScale = false;
public bool Canceled
{
get
{
return mCanceled;
}
}
public float Time
{
get { return mTime; }
}
public bool UsingWorldTimeScale
{
get { return mUseWorldTimeScale; }
}
public System.Action<Schedule> Callback
{
get { return mDelegate; }
}
public Schedule()
{
}
public Schedule(float t, System.Action<Schedule> callback)
{
mTime = t;
mDelegate = callback;
}
public Schedule(float t, bool worldTimeScale, System.Action<Schedule> callback)
{
mTime = t;
mUseWorldTimeScale = worldTimeScale;
mDelegate = callback;
}
public void Cancel()
{
mCanceled = true;
}
public void ResetTime(float t)
{
mTime = t;
}
}
使用的时候只需在一个Mono脚本的Update去调用Timer的Update函数,就会每帧遍历计时器,并在每个计时器的 Time <= 0 的时候执行回调。