Skip to content

Instantly share code, notes, and snippets.

@mattyellen
Created July 26, 2020 19:36
Show Gist options
  • Save mattyellen/d63f1f557d08f7254345bff77bfdc8b3 to your computer and use it in GitHub Desktop.
Save mattyellen/d63f1f557d08f7254345bff77bfdc8b3 to your computer and use it in GitHub Desktop.
Allows the use of async/await (instead of yield) with any Unity AsyncOperation
public static class ExtensionMethods
{
public static TaskAwaiter GetAwaiter(this AsyncOperation asyncOp)
{
var tcs = new TaskCompletionSource<object>();
asyncOp.completed += obj => { tcs.SetResult(null); };
return ((Task)tcs.Task).GetAwaiter();
}
}
/* Example:
var getRequest = UnityWebRequest.Get("http://www.google.com");
await getRequest.SendWebRequest();
var result = getRequest.downloadHandler.text;
*/
@thomrobin
Copy link

Thanks! Don't forget libraries since there's more than one AsyncOperation

using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using UnityEngine;

@VinzzF
Copy link

VinzzF commented Mar 31, 2022

This does not seem work with UnityWebRequest when the request fails (i.e. AsyncOperation.isDone is set but AsyncOperation.completed is not invoked). In this case it makes the Task and awaiting routines hang indefinitely.

This probably can't be solved without continuously checking the AsyncOperation.completed flag somehow?

@UnitTHK
Copy link

UnitTHK commented Oct 26, 2023

Thank you a lot for this! I've been having a headache with making Untiy wait for a web request to complete before doing something in a function. This helps solve it, again thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment