计时器(Timer)
一个基于优先队列的0gc计时器管理器。
将需要定时的class实现ITimer接口(比如Buff、技能之类带有冷却的东西),然后调用TimerManager中的方法开始/停止计时。
当然也可以传入委托进行计时(使用Timer这个class即可),不过这种方法有gc。
示例
下面代码示例了一个简单的技能冷却写法。
https://github.com/VMware233/VMFramework/blob/main/Assets/Examples/Timers/SpellTimerExample.cs
using System;
using Sirenix.OdinInspector;
using UnityEngine;
using VMFramework.Core;
using VMFramework.Timers;
namespace VMFramework.Examples
{
public class SpellTimerExample : ITimer
{
private double expectedTime;
[ShowInInspector]
public float Cooldown
{
get => (float)(expectedTime - TimerManager.currentTime).ClampMin(0);
set
{
if (value <= 0)
{
if (Cooldown > 0)
{
TimerManager.Stop(this);
}
return;
}
if (TimerManager.Contains(this))
{
TimerManager.Stop(this);
}
TimerManager.Add(this, value);
}
}
public event Action<SpellTimerExample> OnCooldownEnd;
#region Timer Implementation
void ITimer.OnStart(double startedTime, double expectedTime)
{
this.expectedTime = expectedTime;
}
void ITimer.OnTimed()
{
OnCooldownEnd?.Invoke(this);
}
#endregion
#region Priority Queue Node Implementation
double IGenericPriorityQueueNode<double>.Priority { get; set; }
int IGenericPriorityQueueNode<double>.QueueIndex { get; set; }
long IGenericPriorityQueueNode<double>.InsertionIndex { get; set; }
#endregion
}
}
最后更新于
这有帮助吗?