Coroutine/Coroutine/CoroutineHandler.cs

61 lines
2.2 KiB
C#
Raw Normal View History

2019-06-22 17:24:50 +02:00
using System;
using System.Collections.Generic;
using System.Linq;
2019-06-22 17:24:50 +02:00
namespace Coroutine {
public static class CoroutineHandler {
private static readonly List<ActiveCoroutine> TickingCoroutines = new List<ActiveCoroutine>();
private static readonly List<ActiveCoroutine> EventCoroutines = new List<ActiveCoroutine>();
2019-06-22 17:24:50 +02:00
public static ActiveCoroutine Start(IEnumerator<IWait> coroutine) {
if (!coroutine.MoveNext())
return null;
var inst = new ActiveCoroutine(coroutine);
var type = inst.GetCurrentType();
if (type == WaitType.Tick)
TickingCoroutines.Add(inst);
else if (type == WaitType.Event)
EventCoroutines.Add(inst);
return inst;
2019-06-22 17:24:50 +02:00
}
public static void InvokeLater(IWait wait, Action action) {
Start(InvokeLaterImpl(wait, action));
}
2019-06-22 17:24:50 +02:00
public static void Tick(double deltaSeconds) {
for (var i = TickingCoroutines.Count - 1; i >= 0; i--) {
var coroutine = TickingCoroutines[i];
if (coroutine.Tick(deltaSeconds)) {
TickingCoroutines.RemoveAt(i);
} else if (coroutine.GetCurrentType() != WaitType.Tick) {
TickingCoroutines.RemoveAt(i);
EventCoroutines.Add(coroutine);
2019-06-22 17:24:50 +02:00
}
}
}
public static void RaiseEvent(Event evt) {
for (var i = EventCoroutines.Count - 1; i >= 0; i--) {
var coroutine = EventCoroutines[i];
if (coroutine.OnEvent(evt)) {
EventCoroutines.RemoveAt(i);
} else if (coroutine.GetCurrentType() != WaitType.Event) {
EventCoroutines.RemoveAt(i);
TickingCoroutines.Add(coroutine);
2019-06-22 17:24:50 +02:00
}
}
}
public static IEnumerable<ActiveCoroutine> GetActiveCoroutines() {
return TickingCoroutines.Concat(EventCoroutines);
}
private static IEnumerator<IWait> InvokeLaterImpl(IWait wait, Action action) {
yield return wait;
action();
}
2019-06-22 17:24:50 +02:00
}
}