mirror of
https://github.com/Ellpeck/Coroutine.git
synced 2024-12-22 09:09:23 +01:00
allow stopping coroutines
This commit is contained in:
parent
99de4c0072
commit
bf792e3e73
2 changed files with 28 additions and 8 deletions
|
@ -1,3 +1,4 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Coroutine {
|
||||
|
@ -5,6 +6,8 @@ namespace Coroutine {
|
|||
|
||||
private readonly IEnumerator<IWait> enumerator;
|
||||
public bool IsFinished { get; private set; }
|
||||
public bool WasCanceled { get; private set; }
|
||||
public FinishCallback OnFinished;
|
||||
|
||||
internal ActiveCoroutine(IEnumerator<IWait> 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);
|
||||
|
||||
}
|
||||
}
|
|
@ -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));
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue