Last active
October 3, 2021 19:01
-
-
Save Sov3rain/a11ec425361f95bea9b80e4975e7177a to your computer and use it in GitHub Desktop.
Custom yield instruction to wait inside a Unity coroutine until a callback is called.
This file contains hidden or 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 UrlDownloader | |
{ | |
public static void DownloadText(string url, Action<string> callback); | |
} | |
// Brute force way of doing it | |
IEnumerator MyAsyncFunction() | |
{ | |
var done = false; | |
var result = default(string); | |
UrlDownloader.DownloadText("http://google.com", r => | |
{ | |
result = r; | |
done = true; | |
}); | |
while (done == false) | |
{ | |
yield return result; | |
} | |
Debug.Log("downloaded: " + result); | |
} | |
// Using the custom yield instruction | |
IEnumerator MyAsyncFunction() | |
{ | |
var download = new WaitForCallback<string>( | |
done => UrlDownloader.DownloadText("http://google.com", text => done(text)) | |
); | |
yield return download; | |
Debug.Log("downloaded: " + download.Result); | |
} |
This file contains hidden or 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
using UnityEngine; | |
// Custom yield instruction to wait until a callback is called | |
// by Jackson Dunstan, http://JacksonDunstan.com/articles/3678 | |
// License: MIT | |
public class WaitForCallback<TResult> : CustomYieldInstruction | |
{ | |
public TResult Result { get; private set; } | |
private bool done; | |
public WaitForCallback(Action<Action<TResult>> callCallback) | |
{ | |
callCallback(r => | |
{ | |
Result = r; | |
done = true; | |
}); | |
} | |
override public bool keepWaiting { get { return done == false; } } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment