using System;
using System.Reflection;
using UnityEngine;
public class StateMachine<TStates> where TStates : Enum
{
private TStates initialState;
private TStates currentState;
private MonoBehaviour component;
public StateMachine(MonoBehaviour component)
{
this.component = component;
}
public StateMachine(MonoBehaviour component, TStates initialState)
{
this.component = component;
this.initialState = initialState;
SetState(this.initialState);
}
public void SetState(TStates newState)
{
Type componentType = component.GetType();
if (currentState != null)
{
if (currentState.Equals(newState))
return;
componentType.GetMethod("On" currentState "Exit", BindingFlags.NonPublic | BindingFlags.Instance)?.Invoke(component, null);
}
else
initialState = newState;
currentState = newState;
componentType.GetMethod("On" currentState "Enter", BindingFlags.NonPublic | BindingFlags.Instance).Invoke(component, null);
}
public void Update()
{
Type componentType = component.GetType();
if (currentState != null)
componentType.GetMethod("On" currentState "Update", BindingFlags.NonPublic | BindingFlags.Instance)?.Invoke(component, null);
}
public void Reset()
{
if (initialState != null)
SetState(initialState);
}
}
我有一個有限狀態機,我嘗試自己制作它,它作業正常。但是,人們告訴我它不是型別安全的。
他們告訴我使用 switch 陳述句,但我不知道如何實作它們。
有什么辦法可以讓它打字安全嗎?
uj5u.com熱心網友回復:
public interface IStateHandle<TStates> where TStates : Enum
{
void OnEnter(TStates state);
void OnUpdate(TStates state);
void OnExit(TStates state);
}
public class StateMachine<TStates> where TStates : Enum
{
IStateHandle<TStates> _handle;
TStates _currentState;
public StateMachine(IStateHandle<TStates> handle)
{
_handle = handle;
}
public void Update()
{
_handle.OnUpdate(_currentState);
}
}
uj5u.com熱心網友回復:
例如,您可以將您的狀態替換為僅使用方法的狀態型別,例如:
public interface IState{
void Exit();
void Enter();
void Update();
}
并為您想要的每個狀態提供一個實作。您還可以有一個將每個方法的實作委托給委托的實作。
uj5u.com熱心網友回復:
您可以通過引入公共基類或介面來輕松地使狀態機型別安全,您的狀態應該從這些基類或介面繼承。鑒于此,實作狀態機設計模式非常簡單:
public interface IState
{
void Handle(Context context);
}
public class Walk : IState
{
public void Handle(Context context)
{
context.State = new Shoot();
}
}
public class Shoot : IState
{
public void Handle(Context context)
{
context.State = new Walk();
}
}
public class Context
{
public Context(IState state)
{
this.State = state;
}
public IState State { get; set; }
public void Request()
{
this.State.Handle(this);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/419086.html
標籤:
上一篇:在Unity中添加不同角度的力
