com.alicizax.unity.framework/Runtime/FSM/FsmModule.cs
2025-09-08 10:10:14 +08:00

85 lines
2.3 KiB
C#

using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine;
using UnityEngine.Scripting;
using Object = UnityEngine.Object;
namespace AlicizaX.Fsm.Runtime
{
[Preserve]
internal sealed class FsmModule : IFsmModule
{
private readonly List<IFsmRunner> _active = new List<IFsmRunner>(256);
private readonly List<IFsmRunner> _toRemove = new List<IFsmRunner>(64);
public int Priority => 0;
void IModuleLateUpdate.LateUpdate()
{
RemoveFsm();
}
private void RemoveFsm()
{
if (_toRemove.Count > 0)
{
for (int i = 0; i < _toRemove.Count; i++)
{
var f = _toRemove[i];
MemoryPool.Release(f);
f.Dispose();
_active.Remove(f);
}
_toRemove.Clear();
}
}
void IModuleUpdate.Update(float elapseSeconds, float realElapseSeconds)
{
float dt = Time.deltaTime;
for (int i = 0; i < _active.Count; i++)
{
_active[i].Tick(dt);
}
}
void IModuleAwake.Awake()
{
}
void IModule.Dispose()
{
for (int i = _active.Count - 1; _active.Count > 0; i--)
{
_toRemove.Add(_active[i]);
}
RemoveFsm();
}
private Fsm<T> CreatePooled<T>(FsmConfig<T> cfg, T blackboard, UnityEngine.Object owner = null, Func<int, string> stateNameGetter = null)
where T : class, IMemory
{
var fsm = Fsm<T>.Rent(cfg, blackboard, owner, stateNameGetter);
_active.Add(fsm);
return fsm;
}
public void DestroyFsm<T>(Fsm<T> fsm) where T : class, IMemory
{
if (fsm == null) return;
_toRemove.Add(fsm);
}
public Fsm<T> Create<T>(FsmConfig<T> cfg, UnityEngine.Object owner = null, Func<int, string> stateNameGetter = null)
where T : class, IMemory, new()
{
var bb = MemoryPool.Acquire<T>();
var fsm = CreatePooled(cfg, bb, owner, stateNameGetter);
return fsm;
}
}
}