public interface IState { string Name { get; } Action EnterAction { get; } Action UpdateAction { get; } Action ExitAction { get; } } public class StateMachine<T> where T : IState { private T currentState; private Dictionary<string, IState> stateDict = new Dictionary<string, IState>(); private float updateInterval = 0.1f; private float updateTimer = 0f; public void AddState(T state) { stateDict[state.Name] = state; } public void SetState(string stateName) { if (currentState != null) { currentState.ExitAction(); } currentState = (T)stateDict[stateName]; currentState.EnterAction(); } public void Update() { updateTimer += Time.deltaTime; if (updateTimer >= updateInterval) { if (currentState != null) { currentState.UpdateAction(); } updateTimer = 0f; } } } public class IdleState : IState { public string Name { get { return "Idle"; } } public Action EnterAction { get { return () => { /* Do idle behavior */ }; } } public Action UpdateAction { get { return () => { /* Do idle behavior */ }; } } public Action ExitAction { get { return () => { /* Do idle behavior */ }; } } } public class WalkingState : IState { public string Name { get { return "Walking"; } } public Action EnterAction { get { return () => { /* Do walking behavior */ }; } } public Action UpdateAction { get { return () => { /* Do walking behavior */ }; } } public Action ExitAction { get { return () => { /* Do walking behavior */ }; } } } public class RunningState : IState { public string Name { get { return "Running"; } } public Action EnterAction { get { return () => { /* Do running behavior */ }; } } public Action UpdateAction { get { return () => { /* Do running behavior */ }; } } public Action ExitAction { get { return () => { /* Do running behavior */ }; } } 请使用这段代码写出具体使用示例代码}
时间: 2023-04-05 19:03:45 浏览: 83
Java基于状态模式实现的文档编辑模式切换功能实例
// 创建状态机
StateMachine<IState> stateMachine = new StateMachine<IState>();
// 添加状态
stateMachine.AddState(new IdleState());
stateMachine.AddState(new WalkingState());
stateMachine.AddState(new RunningState());
// 设置初始状态
stateMachine.SetState("Idle");
// 循环更新状态
while (true) {
stateMachine.Update();
}
阅读全文