BITFALL/Assets/BITKit/Core/Interfaces/IStateMachine.cs

73 lines
2.3 KiB
C#
Raw Normal View History

2023-08-12 01:43:24 +08:00
using System;
using System.Collections.Generic;
namespace BITKit.StateMachine
{
2023-10-29 15:27:13 +08:00
public struct EmptyState:IState
{
public bool Enabled { get; set; }
public void Initialize()
{
}
public void OnStateEntry(IState old)
{
}
public void OnStateUpdate(float deltaTime)
{
}
public void OnStateExit(IState old, IState newState)
{
}
}
2023-08-12 01:43:24 +08:00
public interface IState
{
2023-08-23 01:59:40 +08:00
bool Enabled { get; set; }
2023-08-12 01:43:24 +08:00
void Initialize();
2023-08-23 01:59:40 +08:00
void OnStateEntry(IState old);
2023-08-27 02:58:19 +08:00
void OnStateUpdate(float deltaTime);
2023-08-12 01:43:24 +08:00
void OnStateExit(IState old, IState newState);
}
2023-08-23 01:59:40 +08:00
2023-08-12 01:43:24 +08:00
public interface IStateMachine<T> where T : IState
{
2023-08-23 01:59:40 +08:00
bool Enabled { get; set; }
2023-08-12 01:43:24 +08:00
T CurrentState { get; set; }
2023-08-23 01:59:40 +08:00
event Action<T,T> OnStateChanged;
2024-01-27 04:09:57 +08:00
event Action<T> OnStateRegistered;
event Action<T> OnStateUnRegistered;
2023-08-12 01:43:24 +08:00
IDictionary<Type, T> StateDictionary { get; }
2023-08-23 01:59:40 +08:00
void Initialize();
2023-08-27 02:58:19 +08:00
void UpdateState(float deltaTime);
2023-08-23 01:59:40 +08:00
void DisposeState();
void TransitionState<State>() where State : T;
void TransitionState(T state);
2024-01-27 04:09:57 +08:00
void Register(T newState) => throw new NotImplementedException("未实现的接口");
void UnRegister(T newState) => throw new NotImplementedException("未实现的接口");
void InvokeOnStateRegistered(T state){}
void InvokeOnStateUnRegistered(T state){}
}
public static class StateMachineUtils
{
public static void Register<T>(IStateMachine<T> stateMachine, T newState) where T : IState
{
if (stateMachine.StateDictionary.ContainsKey(newState.GetType()))
{
throw new ArgumentException($"State {newState.GetType().Name} already registered");
}
stateMachine.StateDictionary.Add(newState.GetType(), newState);
newState.Initialize();
stateMachine.InvokeOnStateRegistered(newState);
}
public static void UnRegister<T>(this IStateMachine<T> stateMachine, T newState) where T : IState
{
if (!stateMachine.StateDictionary.ContainsKey(newState.GetType())) return;
stateMachine.StateDictionary.Remove(newState.GetType());
stateMachine.InvokeOnStateUnRegistered(newState);
}
2023-08-12 01:43:24 +08:00
}
}