FunGame-Godot/scripts/Chapter/SceneSwitcher.cs
2026-02-03 01:38:51 +08:00

34 lines
864 B
C#

using Godot;
namespace Milimoe.GodotGame;
public class SceneSwitcher
{
public static void ChangeSceneWithSetup<T>(Node node, string scenePath, System.Action<T> setupAction = null) where T : Node
{
PackedScene packedScene = GD.Load<PackedScene>(scenePath);
if (packedScene == null)
{
GD.PrintErr($"场景加载失败: {scenePath}");
return;
}
T newRoot = packedScene.Instantiate<T>();
// 在这里执行你的初始化逻辑
setupAction?.Invoke(newRoot);
// 切换
SceneTree tree = node.GetTree();
Node oldScene = tree.CurrentScene;
if (oldScene != null)
{
tree.Root.RemoveChild(oldScene);
oldScene.QueueFree();
}
tree.Root.AddChild(newRoot);
tree.CurrentScene = newRoot;
}
}