Using coroutines in C# when programming with Unity can feel clunky when you’re used to the Async/Await workflow in other languages or frameworks.
If you’ve worked with coroutines in Unity before, you have probably noticed that it’s tedious to work with return values. To return values from coroutines, you can either extend the coroutine functionality and use your own iterators instead of Unity’s or you can use events to pass values around.
Coroutines can also be harder to read and understand, especially if there’s validations with try/catch. Since you can’t use yield statements inside try/catch blocks, a small coroutine can easily turn difficult to read.
Using async/await statements can be easier to understand, too. You’re calling something that runs in parallel and you can use the await statement to wait for a task to finish.
Tasks are very useful in C# for returning values. Unfortunately, tasks and multithreading don’t work nicely with Unity all the time, specifically with WebGL.
Lucky for us, there’s a library called UniTask by neuecc. UniTask integrates the same async/await functionality from normal tasks into Unity’s player loop and even has methods to change existing code into coroutines. This makes it compatible with web assembly and WebGL. It also supports timeout handling, cancellation tokens, and other standard Task functionalities.
I will leave an example of calling an asynchronous task from synchronous code below. In the code snippet, we set a UI text asynchronously at start. I’m returning a string value after 100ms, but the same logic would apply to web requests or any other code that you would like to run in the background without stopping the main process.