Files
plugin-library/Assets/03.FiniteStateMachine/RunTime/Base/FSMController.cs
2025-03-31 11:23:20 +08:00

135 lines
3.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace Stary.Evo.FiniteStateMachine
{
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))
{
// 添加时初始化
state.Machine = this;
state.OnInit();
states.Add(type, state);
}
else
{
Debug.LogError("该FSMController中已经添加过该状态");
}
}
/* //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("状态已不存在!!!");
}
return false;
}
public void Enter(Type type)
{
if (states.ContainsKey(type))
{
if (IsRunning(type))
{
Debug.LogError("该状态正在进行,无法再次进入!!!");
return;
}
ForceEnter(type);
}
else
{
Debug.LogError("状态已不存在!!!");
}
}
public void ForceEnter(Type type)
{
if (states.ContainsKey(type))
{
SingleState state = states[type];
state.OnEnter();
state.IsRunning = true;
}
else
{
Debug.LogError("状态已不存在!!!");
}
}
public void Exit(Type type)
{
if (states.TryGetValue(type, out SingleState state))
{
if (!IsRunning(type)) return;
state.IsRunning = false;
state.OnExit();
}
else
{
Debug.LogError("状态已不存在!!!");
}
}
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();
// 遍历字典中的每个状态
foreach (var key in states.Keys.ToList())
{
states[key].OnDestory();
// 将每个值设置为 null释放引用
states[key] = null;
}
// 清空字典
states.Clear();
}
}
}