BITKit/Src/Unity/Scripts/Entity/Core/StateBasedComponent.cs

100 lines
2.1 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using BITKit.Entities;
using BITKit.StateMachine;
using UnityEngine;
namespace BITKit.Entities
{
public class StateBasedBehavior<T> : EntityBehavior,IStateMachine<T> where T : IState
{
[SerializeField] private MonoStateMachine<T> stateMachine;
public bool Enabled
{
get => stateMachine.Enabled;
set => stateMachine.Enabled = value;
}
public T CurrentState
{
get => stateMachine.CurrentState;
set => stateMachine.CurrentState = value;
}
public event Action<T, T> OnStateChanged
{
add => stateMachine.OnStateChanged += value;
remove => stateMachine.OnStateChanged -= value;
}
public event Action<T> OnStateRegistered;
public event Action<T> OnStateUnRegistered;
public IDictionary<Type, T> StateDictionary => stateMachine.StateDictionary;
public override void OnAwake()
{
base.OnAwake();
if (stateMachine is null)
{
Debug.LogWarning(GetType().Name);
}
else
{
foreach (var x in stateMachine.states)
{
Entity.Inject(x);
}
stateMachine.Initialize();
}
}
public override void OnDestroyComponent()
{
base.OnDestroyComponent();
CurrentState?.OnStateExit(CurrentState,null);
}
void IStateMachine<T>.Initialize()
{
stateMachine.Initialize();
}
public void UpdateState(float deltaTime)
{
stateMachine.UpdateState(deltaTime);
}
public void DisposeState()
{
stateMachine.DisposeState();
}
public void TransitionState<State>() where State : T
{
stateMachine.TransitionState<State>();
}
public void TransitionState(T state)
{
stateMachine.TransitionState(state);
}
public virtual void Register(T newState)
{
Entity.Inject(newState);
StateMachineUtils.Register(this, newState);
}
public virtual void UnRegister(T newState)=>StateMachineUtils.UnRegister(this,newState);
public void InvokeOnStateRegistered(T state)
{
OnStateRegistered?.Invoke(state);
}
public void InvokeOnStateUnRegistered(T state)
{
OnStateUnRegistered?.Invoke(state);
}
}
}