From bf792e3e734b225ae9ec319bfb3af53c7e484729 Mon Sep 17 00:00:00 2001 From: Ellpeck Date: Sun, 22 Mar 2020 22:28:19 +0100 Subject: [PATCH] allow stopping coroutines --- Coroutine/ActiveCoroutine.cs | 28 ++++++++++++++++++++-------- Coroutine/CoroutineHandler.cs | 8 ++++++++ 2 files changed, 28 insertions(+), 8 deletions(-) diff --git a/Coroutine/ActiveCoroutine.cs b/Coroutine/ActiveCoroutine.cs index 066e0e7..899377e 100644 --- a/Coroutine/ActiveCoroutine.cs +++ b/Coroutine/ActiveCoroutine.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; namespace Coroutine { @@ -5,6 +6,8 @@ namespace Coroutine { private readonly IEnumerator enumerator; public bool IsFinished { get; private set; } + public bool WasCanceled { get; private set; } + public FinishCallback OnFinished; internal ActiveCoroutine(IEnumerator enumerator) { this.enumerator = enumerator; @@ -13,25 +16,34 @@ namespace Coroutine { internal bool Tick(double deltaSeconds) { var curr = this.enumerator.Current; - if (curr != null && curr.Tick(deltaSeconds)) { - if (!this.enumerator.MoveNext()) - this.IsFinished = true; - } + if (curr != null && curr.Tick(deltaSeconds)) + this.MoveNext(); return this.IsFinished; } internal bool OnEvent(Event evt) { var curr = this.enumerator.Current; - if (curr != null && curr.OnEvent(evt)) { - if (!this.enumerator.MoveNext()) - this.IsFinished = true; - } + if (curr != null && curr.OnEvent(evt)) + this.MoveNext(); return this.IsFinished; } + internal void Finish(bool cancel) { + this.IsFinished = true; + this.WasCanceled = cancel; + this.OnFinished?.Invoke(this, cancel); + } + + private void MoveNext() { + if (!this.enumerator.MoveNext()) + this.Finish(false); + } + internal WaitType GetCurrentType() { return this.enumerator.Current.GetWaitType(); } + public delegate void FinishCallback(ActiveCoroutine coroutine, bool canceled); + } } \ No newline at end of file diff --git a/Coroutine/CoroutineHandler.cs b/Coroutine/CoroutineHandler.cs index 7a05a1c..d801e54 100644 --- a/Coroutine/CoroutineHandler.cs +++ b/Coroutine/CoroutineHandler.cs @@ -17,6 +17,14 @@ namespace Coroutine { return inst; } + public static bool Stop(ActiveCoroutine coroutine) { + if (TickingCoroutines.Remove(coroutine) || EventCoroutines.Remove(coroutine)) { + coroutine.Finish(true); + return true; + } + return false; + } + public static void InvokeLater(IWait wait, Action action) { Start(InvokeLaterImpl(wait, action)); }