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 _active = new List(256); private readonly List _toRemove = new List(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 CreatePooled(FsmConfig cfg, T blackboard, UnityEngine.Object owner = null, Func stateNameGetter = null) where T : class, IMemory { var fsm = Fsm.Rent(cfg, blackboard, owner, stateNameGetter); _active.Add(fsm); return fsm; } public void DestroyFsm(Fsm fsm) where T : class, IMemory { if (fsm == null) return; _toRemove.Add(fsm); } public Fsm Create(FsmConfig cfg, UnityEngine.Object owner = null, Func stateNameGetter = null) where T : class, IMemory, new() { var bb = MemoryPool.Acquire(); var fsm = CreatePooled(cfg, bb, owner, stateNameGetter); return fsm; } } }