Godot games run in a scene tree, which always has a root node, the main Viewport
.
The current scene is added as a child of the root.
Viewport
|- CustomizationScene <-- your current scene
When you use change_scene()
, Godot removes the current scene, and instances the next scene in its place.
That means everything in your customization scene is removed, and is no longer accessible in the next scene that replaced it.
Very often, "Auto-load" nodes (or singletons) are used as a solution to this.
change_scene()
doesn't clear the entire scene tree, only the node considered to be the current scene. That means if Viewport
has other children, they will stay alive and can still be accessed. Those nodes are commonly called "singletons", because the use case is to have one of each.
Auto-loads are nodes that are automatically added to the tree that way, and stay alive even if you change the current scene, because those nodes are added as siblings of the current scene:
Viewport
|- CustomizationScene <-- current scene, only this one gets replaced
|- CustomSingleton <-- "auto-load" node, it stays where it is
So, to access your customization variables in your second scene, you can create a script which goes on an auto-load, and store your variables in that node.
Then, in your next scene, you can access that singleton by using get_tree().get_root().get_node("CustomSingleton")
, or get_node("/CustomSingleton")
, which matches where singletons are in the tree.
To simplify this use case, Godot allows you to access such singletons by name from any script, so if you create CustomSingleton
, you can just write print(CustomSingleton.eyes_color)
from anywhere.
See the doc for more info about setting up singletons: https://docs.godotengine.org/en/latest/getting_started/step_by_step/singletons_autoload.html
There are other possible approaches to this problem, for example not using change_scene()
and swap child nodes manually, but the bottom line is, it's just a particular usage of the scene tree :)