- Temporary solution to easily run Coroutines as async code.
- Unity minimum version: 2019.3
- Current version: 1.0.0
- License: MIT
Currently, Unity does not support a proper way to run Coroutines using async/await code.
This will change in the next big update for the Unity .NET environment where asynchronous programing will be improved significantly.
Until there, this package provides a simple way to execute Coroutines asynchronous and improve your code legibility. Use it until Unity provides the official solution.
Simply import the namespace ActionCode.AwaitableCoroutines
and use the asynchronous AwaitableCoroutine.Run()
function to run any Coroutine
in your code.
using UnityEngine;
using System.Collections;
using ActionCode.AwaitableCoroutines;
public sealed class Test : MonoBehaviour
{
public async void Start()
{
await AwaitableCoroutine.Run(CountUntil(5));
print("Counting until five has finished!");
await AwaitableCoroutine.Run(CountUntil(10));
print("Counting until ten has finished!");
}
IEnumerator CountUntil(int seconds)
{
var waitOneSecond = new WaitForSeconds(1);
for (int i = 1; i <= seconds; i++)
{
print("Counting: " + i);
yield return waitOneSecond;
}
}
}
Note: your class does not need to be a
MonoBehaviour
.
The static AwaitableCoroutine
class uses a GameObject with the internal AwaitableCoroutineBehaviour script to wrap and execute asynchronous tasks.
This GameObject is lazy created, i.e. it'll be only created when used for the first time and it'll be sent to the special scene DontDestroyOnLoad. It's cached after that.
For safety, this GameObject cannot be edited using the Inspector. Do not delete this GameObject.
Follow the instructions inside here and the package ActionCode-Awaitable Coroutines will be available for you to install using the Package Manager windows.
You will need a Git client installed on your computer with the Path variable already set.
-
Use the Package Manager "Add package from git URL..." feature and paste this URL:
https://github.com/HyagoOliveira/AwaitableCoroutines.git
-
You can also manually modify you
Packages/manifest.json
file and add this line insidedependencies
attribute:
"com.actioncode.awaitable-coroutines":"https://github.com/HyagoOliveira/AwaitableCoroutines.git"
Hyago Oliveira