Files
plugin-library/Assets/03.FiniteStateMachine/RunTime/FSMController.cs

132 lines
2.9 KiB
C#
Raw Normal View History

2025-03-21 18:34:26 +08:00
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class FSMController : MonoBehaviour
{
private Dictionary<Type, SingleState> states = new Dictionary<Type, SingleState>();
public void AddState(SingleState state)
{
var type = state.GetType();
if (!states.ContainsKey(type))
{
// <20><><EFBFBD><EFBFBD>ʱ<EFBFBD><CAB1>ʼ<EFBFBD><CABC>
state.Machine = this;
state.OnInit();
states.Add(type, state);
}
else
{
Debug.LogError("<22><>FSMController<65><72><EFBFBD>Ѿ<EFBFBD><D1BE><EFBFBD><EFBFBD>ӹ<EFBFBD><D3B9><EFBFBD>״̬<D7B4><CCAC><EFBFBD><EFBFBD><EFBFBD><EFBFBD>");
}
}
/* //public bool IsRunning<T>() where T : SingleState => IsRunning(typeof(T));
//public void Enter<T>() where T : SingleState => Enter(typeof(T));
//public void Exit<T>() where T : SingleState => Exit(typeof(T));
//public void ForceEnter<T>() where T : SingleState => ForceEnter(typeof(T));*/
public bool IsRunning(Type type)
{
if (states.ContainsKey(type))
{
if (states[type].IsRunning) return true;
}
else
{
Debug.LogError("״̬<D7B4>Ѳ<EFBFBD><D1B2><EFBFBD><EFBFBD>ڣ<EFBFBD><DAA3><EFBFBD><EFBFBD><EFBFBD>");
}
return false;
}
public void Enter(Type type)
{
if (states.ContainsKey(type))
{
if (IsRunning(type))
{
Debug.LogError("<22><>״̬<D7B4><CCAC><EFBFBD>ڽ<EFBFBD><DABD>У<EFBFBD><D0A3>޷<EFBFBD><DEB7>ٴν<D9B4><CEBD><EFBFBD><EBA3A1><EFBFBD><EFBFBD>");
return;
}
ForceEnter(type);
}
else
{
Debug.LogError("״̬<D7B4>Ѳ<EFBFBD><D1B2><EFBFBD><EFBFBD>ڣ<EFBFBD><DAA3><EFBFBD><EFBFBD><EFBFBD>");
}
}
public void ForceEnter(Type type)
{
if (states.ContainsKey(type))
{
SingleState state = states[type];
state.OnEnter();
state.IsRunning = true;
}
else
{
Debug.LogError("״̬<D7B4>Ѳ<EFBFBD><D1B2><EFBFBD><EFBFBD>ڣ<EFBFBD><DAA3><EFBFBD><EFBFBD><EFBFBD>");
}
}
public void Exit(Type type)
{
if (states.TryGetValue(type, out SingleState state))
{
if (!IsRunning(type)) return;
state.IsRunning = false;
state.OnExit();
}
else
{
Debug.LogError("״̬<D7B4>Ѳ<EFBFBD><D1B2><EFBFBD><EFBFBD>ڣ<EFBFBD><DAA3><EFBFBD><EFBFBD><EFBFBD>");
}
}
public void ExitAll()
{
foreach (var state in states)
{
if (state.Value.IsRunning) Exit(state.Key);
}
}
private void Update()
{
foreach (var state in states)
{
if (state.Value.IsRunning) state.Value.Update();
}
}
private void FixedUpdate()
{
foreach (var state in states)
{
if (state.Value.IsRunning) state.Value.FixedUpdate();
}
}
private void OnDestroy()
{
ExitAll();
// <20><><EFBFBD><EFBFBD><EFBFBD>ֵ<EFBFBD><D6B5>е<EFBFBD>ÿ<EFBFBD><C3BF>״̬
foreach (var key in states.Keys.ToList())
{
states[key].OnDestory();
// <20><>ÿ<EFBFBD><C3BF>ֵ<EFBFBD><D6B5><EFBFBD><EFBFBD>Ϊ null<6C><6C><EFBFBD>ͷ<EFBFBD><CDB7><EFBFBD><EFBFBD><EFBFBD>
states[key] = null;
}
// <20><><EFBFBD><EFBFBD><EFBFBD>ֵ<EFBFBD>
states.Clear();
}
}