using System.Collections;
|
using System.Collections.Generic;
|
using UnityEngine;
|
using Cysharp.Threading.Tasks;
|
using System;
|
|
/// <summary>
|
/// 启动状态机
|
/// </summary>
|
public class LaunchStateMachine
|
{
|
// 状态列表
|
private List<ILaunchState> states = new List<ILaunchState>();
|
|
// 当前状态索引
|
private int currentStateIndex = -1;
|
|
// 当前状态
|
private ILaunchState CurrentState => currentStateIndex >= 0 && currentStateIndex < states.Count ? states[currentStateIndex] : null;
|
|
// 状态机是否正在运行
|
private bool isRunning = false;
|
|
// 状态机是否已完成
|
private bool isCompleted = false;
|
|
// 状态机完成事件
|
public event Action OnCompleted;
|
|
/// <summary>
|
/// 添加状态
|
/// </summary>
|
/// <param name="state">状态</param>
|
public void AddState(ILaunchState state)
|
{
|
if (state == null)
|
{
|
Debug.LogError("添加的状态为空");
|
return;
|
}
|
|
states.Add(state);
|
Debug.Log($"添加状态: {state.StateName}");
|
}
|
|
/// <summary>
|
/// 启动状态机
|
/// </summary>
|
public async UniTask Start()
|
{
|
if (isRunning)
|
{
|
Debug.LogWarning("状态机已经在运行中");
|
return;
|
}
|
|
if (states.Count == 0)
|
{
|
Debug.LogError("状态机中没有状态");
|
return;
|
}
|
|
isRunning = true;
|
isCompleted = false;
|
currentStateIndex = 0;
|
|
Debug.Log("启动状态机");
|
|
// 进入第一个状态
|
await EnterCurrentState();
|
|
// 开始执行状态机
|
await ExecuteStateMachine();
|
}
|
|
/// <summary>
|
/// 停止状态机
|
/// </summary>
|
public async UniTask Stop()
|
{
|
if (!isRunning)
|
{
|
return;
|
}
|
|
// 退出当前状态
|
if (CurrentState != null)
|
{
|
await CurrentState.OnExit();
|
}
|
|
isRunning = false;
|
Debug.Log("停止状态机");
|
}
|
|
/// <summary>
|
/// 进入当前状态
|
/// </summary>
|
private async UniTask EnterCurrentState()
|
{
|
if (CurrentState != null)
|
{
|
Debug.Log($"进入状态: {CurrentState.StateName}");
|
await CurrentState.OnEnter();
|
}
|
}
|
|
/// <summary>
|
/// 执行状态机
|
/// </summary>
|
private async UniTask ExecuteStateMachine()
|
{
|
while (isRunning && currentStateIndex < states.Count)
|
{
|
// 执行当前状态
|
bool moveToNext = await CurrentState.OnExecute();
|
|
if (moveToNext)
|
{
|
// 退出当前状态
|
await CurrentState.OnExit();
|
|
// 移动到下一个状态
|
currentStateIndex++;
|
|
// 如果还有下一个状态,则进入
|
if (currentStateIndex < states.Count)
|
{
|
await EnterCurrentState();
|
}
|
else
|
{
|
// 所有状态已执行完毕
|
isRunning = false;
|
isCompleted = true;
|
Debug.Log("状态机执行完毕");
|
OnCompleted?.Invoke();
|
}
|
}
|
|
// 等待一帧,避免卡死
|
await UniTask.Yield();
|
}
|
}
|
}
|