Skip to content

Instantly share code, notes, and snippets.

@ntratcliff
Created June 28, 2022 15:40
Show Gist options
  • Save ntratcliff/9f14b619d50c00ceddccd5a73d443f5c to your computer and use it in GitHub Desktop.
Save ntratcliff/9f14b619d50c00ceddccd5a73d443f5c to your computer and use it in GitHub Desktop.
A custom yield instruction that waits for an arbitrary event
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