Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing C# 5 async to wait for something that executes over a number of game frames
    text
    copied!<p>My son is writing a simple RPG game that has a number of non-player characters (aka NPC's). Each NPC has an associated "script" that controls its behaviour. We were going to use a mini custom script language to write these behaviours but I'm now wondering if this would be better done in C#5/Async.</p> <p>Taking a really simple example, suppose one of the NPC's just walks between two points I'm thinking it would be nice to write something like this:</p> <pre><code>while (true) { await WalkTo(100,100); await WalkTo(200,200); } </code></pre> <p>The WalkTo method would be an async method that handles everything to do with walking between the two points and does this over a number of frames from the game loop. It's not a blocking method that can be off-loaded to a background thread.</p> <p>And this is where I'm stuck... I haven't been able to find any examples using async/await in this manner, but it seems it would be perfect for it.</p> <p>Ideas?</p> <hr> <p>Here's some very rough pseudo code for what I'd like to do:</p> <pre><code>class NpcBase { // Called from game loop public void onUpdate(double elapsedTime) { // Move the NPC . . . // Arrived at destination? if (Arrived) { // How do I trigger that the task is finished? _currentTask.MarkComplete(); } } // Async method called by NPC "script" public async Task WalkTo(int x, int y) { // Store new target location // return a task object that will be "triggered" when the walk is finished _currentTask = &lt;something??&gt; return _currentTask; } Task _currentTask; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload