using Godot;

public partial class SceneHandler : Node
{
  private Node _root;

  // Called when the node enters the scene tree for the first time.
  public override void _Ready()
  {
    _root = GetTree().Root.GetChild(GetChildCount() - 1);
    GD.Print(_root.GetChildren());
  }

  public void OnLoadScene(string path)
  {
    CallDeferred(nameof(DeferredGoToScene), path);
  }

  private void DeferredGoToScene(string path)
  {
    var currentScene = _root.GetChild(_root.GetChildCount() - 1);

    var nextScene = (PackedScene)GD.Load(path);

    _root.RemoveChild(currentScene);

    currentScene = nextScene.Instantiate();

    _root.AddChild(currentScene);
  }
}
