using EasyInject.Attributes; using System; using System.Collections.Generic; using UnityEngine; /// /// 程序状态机 /// [Component] public class ApplicationStateMachine { private List processStates; private static IProcessState currentProcess ; private static ApplicationStateMachine stateMachine; public event ProcessCompleted ProcessCompletedEvent; public delegate void ProcessCompleted(); public ApplicationStateMachine() { stateMachine = this; } private static void SetCurrentProcess(IProcessState current) { current.IsExecuteProcess = true; currentProcess = current; int index = stateMachine.processStates.IndexOf(currentProcess); try { current.OnEnter(); }catch (Exception ex) { Debug.LogError(ex.Message); } //已经是最后流程了,触发完成事件 if (index == stateMachine.processStates.Count - 1) { stateMachine.ProcessCompletedEvent?.Invoke(); } } /// /// 切换下一个流程,根据流程优先级切换 /// public static void Chanage(IProcessState currentProcess) { int index = stateMachine.processStates.IndexOf(currentProcess) + 1; if (stateMachine.processStates.Count != index && stateMachine.processStates[index] != null) { currentProcess.IsExecuteProcess = false; currentProcess.OnExit(); SetCurrentProcess(stateMachine.processStates[index]); } } public void OnInit() { Debug.Log("初始化状态机"); processStates = ApplicationBoot.Instance.GetBeans(); if (processStates != null && processStates.Count > 0) { processStates.Sort((a, b) => a.Priority - b.Priority); SetCurrentProcess(processStates[0]); } } /// /// 每帧更新状态机 /// public void OnUpdate() { if (currentProcess != null) { try { currentProcess.OnUpdate(); } catch (Exception ex) { Debug.LogError(ex.Message); } } } }