68 lines
2.1 KiB
C#
68 lines
2.1 KiB
C#
using System;
|
|
using System.Collections;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
namespace BITKit.StateMachine
|
|
{
|
|
[System.Serializable]
|
|
public abstract class MonoStateMachine<TState> : IStateMachine<TState>, IMonoProxy, IStart, IUpdate
|
|
where TState : IState
|
|
{
|
|
[Header(Constant.Header.Settings)]
|
|
public string name;
|
|
[Header(Constant.Header.Settings)]
|
|
[SerializeField, SerializeReference, SubclassSelector]
|
|
TState currentState;
|
|
public TState CurrentState
|
|
{
|
|
get => currentState;
|
|
set => currentState = value;
|
|
}
|
|
[Header(Constant.Header.Components)]
|
|
[SerializeReference, SubclassSelector] public List<TState> states = new();
|
|
public IDictionary<System.Type, TState> StateDictionary { get; } = new Dictionary<Type, TState>();
|
|
public IStateMachine<TState> StateMachine => this as IStateMachine<TState>;
|
|
TState tempState;
|
|
public virtual void OnStart()
|
|
{
|
|
foreach (var state in states)
|
|
{
|
|
//state.TransitionState = InternalTransitionState;
|
|
state.Initialize();
|
|
StateDictionary.Add(state.GetType(), state);
|
|
}
|
|
if (states.Count > 0)
|
|
{
|
|
var index = states[0];
|
|
StateMachine.TransitionState(index);
|
|
}
|
|
}
|
|
public virtual void ExitState()
|
|
{
|
|
CurrentState?.OnStateExit(CurrentState, null);
|
|
CurrentState = default;
|
|
}
|
|
public virtual void RecoveryState()
|
|
{
|
|
if (tempState is not null)
|
|
{
|
|
StateMachine.TransitionState(tempState);
|
|
}
|
|
else
|
|
{
|
|
StateMachine.TransitionState(states[0]);
|
|
}
|
|
}
|
|
public virtual void OnUpdate(float deltaTime)
|
|
{
|
|
CurrentState?.OnStateUpdate();
|
|
}
|
|
void InternalTransitionState(IState state)
|
|
{
|
|
if (state is TState tState)
|
|
{
|
|
StateMachine.TransitionState(tState);
|
|
}
|
|
}
|
|
}
|
|
} |