IndieGame/client/Assets/Ether/Scripts/Module/StateMachine/StateMachine.cs

46 lines
1.2 KiB
C#
Raw Normal View History

2024-10-11 10:12:15 +08:00
using System;
using System.Collections.Generic;
2024-10-30 17:58:20 +08:00
using Sirenix.OdinInspector;
2024-10-11 10:12:15 +08:00
namespace Ether
{
2024-10-30 17:58:20 +08:00
public abstract class StateMachine : Entity
2024-10-11 10:12:15 +08:00
{
2024-10-30 17:58:20 +08:00
private StateBase currentState;
[ShowInInspector]
[LabelText("状态列表")]
public List<StateBase> allStates = new List<StateBase>();
private DictionaryEx<string, StateBase> allStatesDic = new DictionaryEx<string, StateBase>();
2024-10-11 10:12:15 +08:00
private void Awake()
{
2024-10-30 17:58:20 +08:00
foreach (var state in allStates)
2024-10-11 10:12:15 +08:00
{
2024-10-30 17:58:20 +08:00
state.StateMachine = this;
allStatesDic.TryAdd(state.GetType().Name, state);
2024-10-11 10:12:15 +08:00
}
}
2024-10-30 17:58:20 +08:00
public void ChangeState<T>() where T : StateBase
2024-10-11 10:12:15 +08:00
{
2024-10-30 17:58:20 +08:00
ChangeState(typeof(T).Name);
2024-10-11 10:12:15 +08:00
}
2024-10-30 17:58:20 +08:00
public void ChangeState(string stateName)
2024-10-11 10:12:15 +08:00
{
2024-10-30 17:58:20 +08:00
if (allStatesDic.TryGetValue(stateName, out var state) && state != currentState)
2024-10-11 10:12:15 +08:00
{
2024-10-30 17:58:20 +08:00
currentState?.Exit();
currentState = state;
currentState.Enter();
2024-10-11 10:12:15 +08:00
}
}
2024-10-30 17:58:20 +08:00
private void Update()
2024-10-11 10:12:15 +08:00
{
2024-10-30 17:58:20 +08:00
currentState?.Execute();
2024-10-11 10:12:15 +08:00
}
}
2024-10-30 17:58:20 +08:00
}