Files
plugin-library/Assets/03.FiniteStateMachine/RunTime/Use/FSMInitialize.cs
2025-03-31 11:23:20 +08:00

51 lines
1.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace Stary.Evo.FiniteStateMachine
{
public static class FSMInitialize
{
/// <summary>
/// 状态机初始化
/// </summary>
/// <param name="targetScene">指定场景</param>
/// <returns></returns>
public static FSMManager Init(Scene targetScene)
{
GameObject targetObject = targetScene.GetRootGameObjects().FirstOrDefault(go => go.name == "FSMManger");
FSMManager fSMManager;
if (targetObject == null)
{
targetObject = new GameObject("FSMManger");
SceneManager.MoveGameObjectToScene(targetObject, targetScene);
fSMManager = new FSMManager();
fSMManager.FSMMangerObject = targetObject;
void OnSceneUnloaded(Scene scene)
{
// 当场景卸载时释放缓存
if (scene.name == targetScene.name)
{
GameObject.Destroy(targetObject);
fSMManager = null;
}
}
SceneManager.sceneUnloaded += OnSceneUnloaded;
return fSMManager;
}
else
{
Debug.LogError("场景: " + targetScene.name + "已经初始化过FSM状态机");
return null;
}
}
}
}