gpt4 book ai didi

C#如何用单个定时器通知其他类?

转载 作者:太空宇宙 更新时间:2023-11-03 13:06:02 24 4
gpt4 key购买 nike

我正在尝试制作一个全局计时器,在经过一定时间后需要通知所有内容。

例如,在游戏中,会有增益和攻击冷却计时器以及元素冷却等等。

单独管理它们很好,但我如何让它们都在同一个计时器上运行?

我曾尝试使用 SortedList,将 float 作为键,将委托(delegate)作为值,以便在时间到了时简单地调用它,但我似乎无法管理它。尝试使用通用参数进行委托(delegate),但我无法将其放入排序列表中。

谁能指出我正确的方向?

最佳答案

我可以指出两个选项:

  1. 创建一个类似 TimerControlled 的接口(interface)(所有名称都可以更改)使用方法 TimerTick(whatever arguments you need) (以及其他需要的参数),它实现了你的计时器该类的勾选逻辑。在使用定时器相关机制的每个类上实现接口(interface)。最后,在您的基础(逻辑)类上,将所有 TimerControlled 对象添加到一个数组(TimerControlled),这将允许您循环遍历该数组并调用这些对象的 TimerTick 方法带有 2 行代码的对象。

接口(interface):

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();
}
}

}
  1. (从长远来看,这不是一个很好的选择)静态类中的静态计时器,如 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();
}
}

请记住,我是凭空编写代码,因此可能存在一些语法错误,但逻辑是正确的。

如果您对答案还有其他问题,请提出。

关于C#如何用单个定时器通知其他类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30772548/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com