Created
July 26, 2020 19:36
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
*/ |
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
This does not seem work with
UnityWebRequest
when the request fails (i.e.AsyncOperation.isDone
is set butAsyncOperation.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?