11
\$\begingroup\$

I'm looking for a generic / reusable way to wait for coroutines and asynchronous operations to finish in Unity 5, similiar to C#5's await keyword.

The simplest way I can think of is something like this:

 public class SomeUtility {
     public bool IsDoingSomething { get; private set; }

     public IEnumerator DoSomethingAsync() {
         IsDoingSomething = true;
         yield return new WaitForSeconds(2);
         IsDoingSomething = false;
     }
 }

and then in another coroutine:

 while(!someUtilityInstance.IsDoingSomething)
     yield return null;

However this is not very nice because it clutters the code with while statements, is not reusable (needs instances and dedicated classes even for simple utility functions!) and a lot of singleton or static stuff where it's not even needed.

The closest I found is using Unity's AsyncOperation. This here works very nicely:

public static IEnumerator Await(this AsyncOperation operation) {
    while(!operation.isDone)
        yield return operation;
}

yield return SceneManager.LoadLevelAsync("blaaaah").Await();

However.. the problem is: How to create an AsyncOperation? A few services, for examples SceneManager are using it, but the documentation completely lacks anything about creating custom operations or wrapping existing coroutines etc.

So, is there a way to create a simple, generic and resuable "await" for custom coroutines?

\$\endgroup\$
  • \$\begingroup\$ Perhaps use reflection and callbacks? Pass two methods into a coroutines. The first one the method to do. Use reflection to see when it finishes, then call the second one \$\endgroup\$ – Evorlor Jun 21 '16 at 1:04
2
\$\begingroup\$
yield return StartCoroutine(yourIEnumatorMethod());

Will wait until your method has completed, the only inconvenient with that solution is it forces you to make this call within an IEnumator method.

See http://docs.unity3d.com/ScriptReference/Coroutine.html

\$\endgroup\$
1
\$\begingroup\$

With Unity 2017 you can now use async await as an alternative to coroutines as described here

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.