How do I change scenes from within a SubViewport?

Godot Version

v4.4.1.stable.official [49a5bc7b6]

Question

I am very, very new to using Godot, and in my game, I have chosen to use a Subviewport to separate my game’s UI nodes and gameplay scenes to keep resolutions looking nice. My issue is that I don’t know how to access and change the gameplay scene between levels from within the main scene tree. I can’t just use get_tree().change_scene_to_file() since that would change the entire main scene to just the level without the UI or correct resolution scaling.

If it helps, my main scene tree looks like this:

  • main
    CanvasLayerSubViewportContainer

All get_tree().change_scene_to_file() does is:

  1. Load the scene at the given path
  2. Destroy the current scene (the child of root)
  3. Instantiate the new scene as a child of root

So to change the gameplay scene:

  1. Get the node you want to act as root, i.e. the future parent of the scene
  2. Get the current gameplay node (you should probably store it in the script that’s responsible for changing scenes)
  3. Free the current node from (2)
  4. Instantiate the new scene and add the node to the parent from (1)