Skip to content

Instantly share code, notes, and snippets.

@Sov3rain
Last active October 3, 2021 19:01
Show Gist options
  • Save Sov3rain/a11ec425361f95bea9b80e4975e7177a to your computer and use it in GitHub Desktop.
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.
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);
}
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