I am currently writing a programm in c#, for which I need something simular to the Update method in the Unity Engine. Basically a loop that executes a given code, over and over again, at a given tick rate. To re-create this functionality I was planing on just using a while (true)
loop and somehow run it without holding up the rest of my thread. Is there any way to do this? My current approach looks like this.
public void Update(int tickrate)
{
while (true)
{
foreach (IAgent agent in Agents)
{
agent.Move();
}
Task.Delay(tickrate / 60);
}
}
CodePudding user response:
This could be a good use-case for the new PeriodicTimer in .Net 6.
Here's a good video explaining it.
Your game loop could look something like this.
public async Task RunGame()
{
// Create the timer by defining the period.
// I used a period of 1/60 seconds (which would result in 60 updates per second).
var timer = new PeriodicTimer(TimeSpan.FromSeconds(1.0/60));
while (true)
{
foreach (IAgent agent in Agents)
{
agent.Move();
}
// WaitForNextTickAsync waits for the right amount of time
// by considering the time spent updating the game state.
await timer.WaitForNextTickAsync(CancellationToken.None);
}
}
Note that I used CancellationToken.None
for brevity/simplicity. It would make sense to pass a CancellationToken
as an argument of the RunGame
method.