我正在尝试创建一个全局计时器,在经过一定时间后需要通知的所有内容。
例如,在游戏中,会有buff,攻击冷却计时器和物品冷却等等。
单独管理它们很好,但是我如何使它们全部在同一计时器上运行?
我尝试过使用SortedList,将浮点数作为键并将委托作为值在时间到时可以简单地调用,但是我似乎无法管理它。尝试了具有泛型参数的委托,但我无法将其放入排序列表中。
谁能指出我正确的方向?
我可以指出2个选择:
TimerControlled
使用方法TimerTick(whatever arguments you need)
(可以根据需要更改其他名称)来创建一个接口((可以更改所有名称)),该接口实现该类的计时器滴答逻辑。在使用计时器相关机制的每个类上实现接口。最后,在您的基础(逻辑)类上,将所有TimerControlled
对象添加到一个数组中TimerControlled
,以允许您循环访问该数组,并用两行代码调用这些对象的TimerTick方法。界面:
interface TimerControlled
{
void TimerTick();
}
在您的每个课程中实现它:
public class YourClass: TimerControlled{
....
public void TimerTick(){
advanceCooldown();
advanceBuffTimers();
}
}
最后将您的课程添加到以下列表TimerControlled
:
class YourLogicClass{
List<YourClass> characters= new List<YourClass>();
private timer;
List<TimerControlled> timerControlledObjects = new List<TimerControlled>();
...
public void Initialize(){
... //your code, character creation and such
foreach(YourClass character in characters){ //do the same with all objects that have TimerControlled interface implemented
timerControlledObjects.add(character);
}
timer = new Timer();
timer.Tick += new EventHandler(timerTick)
timer.Start();
}
public void timerTick(Object sender, EventArgs e){
foreach(TimerControlled timerControlledObject in timerControlObjects){
timerControlledObject.TimerTick();
}
}
}
Global.timer
,这不是一个很好的选择)静态类(例如)中的静态计时器,这意味着该计时器仅存在1个实例。然后将事件处理程序附加到每个相关类的计时器上,以处理计时器滴答声。代码:
public static class Global{
//I usually create such class for global settings
public static Timer timer= new Timer();
}
class YourLogicClass{
public void Initialize(){
...
Global.timer.Start();
}
}
class YourClass{
public YourClass(){
Global.timer.tick += new EventHandler(timerTick);
}
private void timerTick(Object sender,EventArgs e){
advanceCooldowns();
advanceBuffTimers();
}
}
请记住,我已经把代码写在了脑海中,所以可能存在一些语法错误,但是逻辑是正确的。
如果您对答案还有其他疑问,请离开。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句