AK056/Assets/script/application/ApplicationStateMachine.cs
2025-05-07 11:20:40 +08:00

86 lines
2.2 KiB
C#

using EasyInject.Attributes;
using System;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 程序状态机
/// </summary>
[Component]
public class ApplicationStateMachine
{
private List<IProcessState> 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();
}
}
/// <summary>
/// 切换下一个流程,根据流程优先级切换
/// </summary>
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<IProcessState>();
if (processStates != null && processStates.Count > 0)
{
processStates.Sort((a, b) => a.Priority - b.Priority);
SetCurrentProcess(processStates[0]);
}
}
/// <summary>
/// 每帧更新状态机
/// </summary>
public void OnUpdate()
{
if (currentProcess != null)
{
try
{
currentProcess.OnUpdate();
}
catch (Exception ex)
{
Debug.LogError(ex.Message);
}
}
}
}