I am attempting to implement co-routines in C# in order to make my life easier when it comes to scripting enemy behavior in my game. The game is fixed framerate. What would be an ideal syntax for writing the scripts would be:
wait(60)
while(true)
{
shootAtPlayer();
wait(30);
}
Which means wait 60 frames, shoot at player, wait 30, shoot at player, wait 30... e.t.c.
I have sort of implemented this solution using yield return in C#:
public IEnumerable update()
{
yield return 60;
while(true)
{
shootAtPlayer();
yield return 30;
}
}
The caller keeps a stack of alive routines (0 on the IEnumerable counter) and sleeping routines ( > 0). Every frame the caller reduces the sleeping frame counter of each sleeping routine by 1 until one reaches 0. This routine is made alive again and continues execution until the next yield return. This works fine in most cases but it is annoying that the subroutine cannot be split up like below:
public IEnumerable update()
{
yield return 60;
while(true)
{
doSomeLogic()
yield return 30;
}
}
public IEnumerable doSomeLogic()
{
somethingHappening();
yield return 100;
somethingElseHappens();
}
The above syntax is incorrect as yield return cannot be nested within another method meaning the execution state can only ever be maintained in a single method (the update() in this case). This is a limitation of the yield return statement and I couldn't really find a way to work around it.
I am now trying to implement the same thing using the C# async await keyword, but I couldn't get my head around how to implement a way to cause a wait for x frames before continuing. I saw ways to get the tasks to sleep for x frames but not a way to easily control specific waiting for frames from the caller. Can anyone give me some pointers on how to implement functionally like what I want above using await?