SBC Games has published a great new tutorial that will be of special interest to those who straddle the Unity / Phaser developer line: "If you are familiar with Unity, you may be used to work with coroutines. These are special methods whose execution can be suspended at specific points and resumed after a condition is met. They are handy for executing a sequence of steps.

In this tutorial I will show code for providing similar functionality in Phaser. We will use Javascript generator functions and build a small coroutine manager around it.

Generator functions

Regular functions look like this:

function foo() {
    console.log("Hi!");
}

While generator functions look like this:

function* foo() {
    console.log("Hi!");
}

The asterisk is separate symbol and can be placed close to function keyword function foo() or close to function name function foo().

When you call regular foo() function, it is executed immediately and “Hi!” shows in the console output. When you call the version with asterisk, nothing happens. It is because Generator object is returned instead of immediate execution and you have to call next() on it to start the execution:

const generator = foo();
generator.next();

So, execution is deferred until you call next(). Still nothing super useful. But, you can put keyword yield in the middle of your generator function and then interesting things start to happen ...

Read the full Tutorial