Skip to content

Instantly share code, notes, and snippets.

@JanikHelbig
Last active June 24, 2022 06:54
Show Gist options
  • Save JanikHelbig/8228e3fc6e118757faa8a61c3d8370af to your computer and use it in GitHub Desktop.
Save JanikHelbig/8228e3fc6e118757faa8a61c3d8370af to your computer and use it in GitHub Desktop.
Simple async EventHandler in Unity using Cysharp/UniTask
using System;
using UniRx.Async;
public delegate UniTask EventHandlerAsync(object sender, EventArgs e);
public static class EventHandlerAsyncExtensions
{
public static UniTask InvokeAsync(this EventHandlerAsync handler, object sender, EventArgs e)
{
Delegate[] delegates = handler?.GetInvocationList();
if (delegates == null || delegates.Length == 0)
return UniTask.CompletedTask;
var tasks = new UniTask[delegates.Length];
for (var i = 0; i < delegates.Length; i++)
{
tasks[i] = (UniTask) delegates[i].DynamicInvoke(sender, e);
}
return UniTask.WhenAll(tasks);
}
}
public class Example : MonoBehaviour
{
public event EventHandlerAsync ExampleEvent;
private void Start()
{
StartTest();
}
private async void StartTest()
{
await WaitForAll.InvokeAsync(this, EventArgs.Empty);
}
}
@JanikHelbig
Copy link
Author

Github refuses to use save any other TabWidth than 8 spaces for this gist, just know I'm not a monster...

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