46 lines
1.2 KiB
C#
46 lines
1.2 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using Sirenix.OdinInspector;
|
|
|
|
namespace Ether
|
|
{
|
|
public abstract class StateMachine : Entity
|
|
{
|
|
private StateBase currentState;
|
|
|
|
[ShowInInspector]
|
|
[LabelText("状态列表")]
|
|
public List<StateBase> allStates = new List<StateBase>();
|
|
|
|
private DictionaryEx<string, StateBase> allStatesDic = new DictionaryEx<string, StateBase>();
|
|
|
|
private void Awake()
|
|
{
|
|
foreach (var state in allStates)
|
|
{
|
|
state.StateMachine = this;
|
|
allStatesDic.TryAdd(state.GetType().Name, state);
|
|
}
|
|
}
|
|
|
|
public void ChangeState<T>() where T : StateBase
|
|
{
|
|
ChangeState(typeof(T).Name);
|
|
}
|
|
|
|
public void ChangeState(string stateName)
|
|
{
|
|
if (allStatesDic.TryGetValue(stateName, out var state) && state != currentState)
|
|
{
|
|
currentState?.Exit();
|
|
currentState = state;
|
|
currentState.Enter();
|
|
}
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
currentState?.Execute();
|
|
}
|
|
}
|
|
} |