Last active
June 24, 2022 06:54
-
-
Save JanikHelbig/8228e3fc6e118757faa8a61c3d8370af to your computer and use it in GitHub Desktop.
Simple async EventHandler in Unity using Cysharp/UniTask
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
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); | |
} | |
} |
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 class Example : MonoBehaviour | |
{ | |
public event EventHandlerAsync ExampleEvent; | |
private void Start() | |
{ | |
StartTest(); | |
} | |
private async void StartTest() | |
{ | |
await WaitForAll.InvokeAsync(this, EventArgs.Empty); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Github refuses to use save any other TabWidth than 8 spaces for this gist, just know I'm not a monster...