Created
June 28, 2022 15:40
-
-
Save magnoahlia/9f14b619d50c00ceddccd5a73d443f5c to your computer and use it in GitHub Desktop.
A custom yield instruction that waits for an arbitrary event
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 System; | |
using MacSalad.Core.Events; | |
using UnityEngine; | |
namespace AeLa.Utilities | |
{ | |
public class WaitForEvent<T> : CustomYieldInstruction | |
where T : MSEvent | |
{ | |
public override bool keepWaiting => keepWaitingInternal; | |
protected bool keepWaitingInternal = true; | |
private readonly Func<T, bool> predicate; | |
public WaitForEvent(Func<T, bool> predicate = null) | |
{ | |
this.predicate = predicate; | |
EventDispatcher.AddListener<T>(EventListener); | |
} | |
protected virtual void EventListener(T e) | |
{ | |
keepWaitingInternal = !predicate?.Invoke(e) ?? false; | |
// remove listener if we're done waiting | |
if (!keepWaitingInternal) | |
{ | |
EventDispatcher.RemoveListener<T>(EventListener); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment