Coroutine/Coroutine/ActiveCoroutine.cs

83 lines
2.9 KiB
C#
Raw Normal View History

2020-03-22 22:28:19 +01:00
using System;
2019-06-22 17:24:50 +02:00
using System.Collections.Generic;
namespace Coroutine {
2020-06-13 03:12:26 +02:00
/// <summary>
/// A reference to a currently running coroutine.
/// This is returned by <see cref="CoroutineHandler.Start(IEnumerator{Wait})"/>.
/// </summary>
public class ActiveCoroutine {
2019-06-22 17:24:50 +02:00
private readonly IEnumerator<Wait> enumerator;
private Wait current;
2020-06-13 03:12:26 +02:00
/// <summary>
/// This property stores whether or not this active coroutine is finished.
/// A coroutine is finished if all of its waits have passed, or if it <see cref="WasCanceled"/>.
/// </summary>
public bool IsFinished { get; private set; }
2020-06-13 03:12:26 +02:00
/// <summary>
/// This property stores whether or not this active coroutine was cancelled using <see cref="Cancel"/>.
/// </summary>
2020-03-22 22:28:19 +01:00
public bool WasCanceled { get; private set; }
2020-06-13 03:12:26 +02:00
/// <summary>
/// An event that gets fired when this active coroutine finishes or gets cancelled.
/// When this event is called, <see cref="IsFinished"/> is always true.
/// </summary>
public event FinishCallback OnFinished;
2019-06-22 17:24:50 +02:00
internal ActiveCoroutine(IEnumerator<Wait> enumerator) {
2019-06-22 17:24:50 +02:00
this.enumerator = enumerator;
}
2020-06-13 03:12:26 +02:00
/// <summary>
/// Cancels this coroutine, causing all subsequent <see cref="Wait"/>s and any code in between to be skipped.
/// </summary>
/// <returns>Whether the cancellation was successful, or this coroutine was already cancelled or finished</returns>
public bool Cancel() {
if (this.IsFinished || this.WasCanceled)
return false;
this.WasCanceled = true;
this.IsFinished = true;
this.OnFinished?.Invoke(this);
return true;
}
internal bool Tick(double deltaSeconds) {
if (!this.WasCanceled) {
if (this.current.Tick(deltaSeconds))
this.MoveNext();
}
return this.IsFinished;
2019-06-22 17:24:50 +02:00
}
internal bool OnEvent(Event evt) {
if (!this.WasCanceled) {
if (this.current.OnEvent(evt))
this.MoveNext();
}
return this.IsFinished;
2019-06-22 17:24:50 +02:00
}
internal bool MoveNext() {
if (!this.enumerator.MoveNext()) {
this.IsFinished = true;
this.OnFinished?.Invoke(this);
return false;
}
this.current = this.enumerator.Current;
return true;
2020-03-22 22:28:19 +01:00
}
internal bool IsWaitingForEvent() {
return this.current.IsWaitingForEvent();
2019-06-22 17:24:50 +02:00
}
2020-06-13 03:12:26 +02:00
/// <summary>
/// A delegate method used by <see cref="ActiveCoroutine.OnFinished"/>.
/// </summary>
/// <param name="coroutine">The coroutine that finished</param>
public delegate void FinishCallback(ActiveCoroutine coroutine);
2020-03-22 22:28:19 +01:00
2019-06-22 17:24:50 +02:00
}
}