title: Using await keyword to implement co-routines for game scripts
body: <p>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:</p>
  
  <pre><code>wait(60)
  while(true)
  {
    shootAtPlayer();
    wait(30);
  }
  </code></pre>
  
  <p>Which means wait 60 frames, shoot at player, wait 30, shoot at player, wait 30... e.t.c.</p>
  
  <p>I have sort of implemented this solution using yield return in C#:</p>
  
  <pre><code>public IEnumerable update()
  {
    yield return 60;
    while(true)
    {
      shootAtPlayer();
      yield return 30;
    }
  }
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>public IEnumerable update()
  {
    yield return 60;
    while(true)
    {
      doSomeLogic()
      yield return 30;
    }
  }
  
  public IEnumerable doSomeLogic()
  {
    somethingHappening();
    yield return 100;
    somethingElseHappens();
  }
  </code></pre>
  
  <p>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.</p>
  
  <p>I asked earlier how might it be possible to implement the desired behaviour using C# and it was mentioned that the await keyword might work well in this situation. I am trying to figure out now how to change the code to use await. Is it possible to nest awaits in called methods like I wanted to do with yield return? also how would I implement a counter using awaits? The caller of the routines would need to be in control of decrementing the waiting frames left for each waiting routine as it will be the one called once per frame. How would I go about implementing this?</p>