Syntriax.Engine/Engine.Core/CoroutineManager.cs

45 lines
1.1 KiB
C#

using System.Collections;
using System.Collections.Generic;
using Syntriax.Engine.Core.Abstract;
namespace Syntriax.Engine.Core;
public class CoroutineManager : HierarchyObjectBase
{
private readonly List<IEnumerator> enumerators = [];
public IEnumerator CreateCoroutine(IEnumerator enumerator)
{
enumerators.Add(enumerator);
return enumerator;
}
public void StopCoroutine(IEnumerator enumerator)
{
enumerators.Remove(enumerator);
}
protected override void OnEnteringHierarchy(IGameManager gameManager)
{
gameManager.OnUpdate += OnUpdate;
}
protected override void OnExitingHierarchy(IGameManager gameManager)
{
gameManager.OnUpdate -= OnUpdate;
}
private void OnUpdate(IGameManager sender, EngineTime time)
{
for (int i = enumerators.Count - 1; i >= 0; i--)
{
if (enumerators[i].Current is ICoroutineYield coroutineYield && coroutineYield.Yield())
continue;
if (!enumerators[i].MoveNext())
enumerators.RemoveAt(i);
}
}
}