First, we have to make sure the method we want to make async is
IEnumerator type, with a special return (return preceded by the
yield keyword) instead the simple return command.
Code: Select all
public IEnumerator MyMethod (params){
//Code
yield return 0;
}
However this also means that the method cannot return nothing except the same IEnumerator object used to make coroutines to work. So, for instance you cannot return the result value from a method that sums two numbers.
Since coroutines works in pretty same way to the one in Unity 3D, if you're familiar with it, you can use both IEnumerator and
Coroutine types to start a method asynchronously.
Code: Select all
//Start a coroutine with IEnumerator type
IEnumerator routine = MyMethod (params);
StartCoroutine (routine);
//Start a coroutine with Coroutine type
Coroutine routine = StartCoroutine (MyMethod (params));
//Start a coroutine without keeping his reference
StartCoroutine (MyMethod (params));
The only reason to use Coroutine rather than IEnumerator to start an async method is that the Coroutine object can keep track if the coroutine has finished, is running, etc...
To stop a coroutine, instead, there are three ways:
Code: Select all
//Stop a coroutine by IEnumerator type reference
IEnumerator A = MyMethod (params);
StopCoroutine(A);
//Stop a coroutine by Coroutine type reference
Coroutine B = MyMethod (params);
StopCoroutine(B);
//Stop a coroutine by method name
StopCoroutine("MyMethod");
The last overload is used if you started coroutines without keeping the object reference, to stop them you are forced to use it and will stop the first found coroutine with that method name.
Is also possible to delay the code execution of coroutines by returning
WaitForSeconds(); with a (float) number in seconds as parameter.
Code: Select all
public IEnumerator SpawnCrate() {
while (true) {
Game.CreateObject("Crate00", Vector2.Zero);
yield return new WaitForSeconds(1f);
}
}
This will make the crate spawn every second (game-time).
Note that writing while (true) loops is only possible in coroutine methods, don't try to invoke the method manually or to write infinite loops outside coroutines because the game will hang!
If you need to know how many coroutines are active you can use
GetRoutinesCount(); like so:
Code: Select all
int CoroutinesCount = Coroutine.GetRoutinesCount();
The class have also these attributes that can be used to known the state of a coroutine:
- bool IsFinished: true if the coroutine has finished the entire method execution, false if is still running or never finished because of a StopCoroutine() invoked.
- bool IsRunning: true if the coroutine is started and it's currently running, false if has finished executing the method or is stopped by StopCoroutine().