Is it possible to make a variable that keep's the value assigned to it across different scenes?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By RowingNoob
:bust_in_silhouette: Reply From: Zylann

Simple answer: yes, with singleton nodes: Singletons (AutoLoad) — Godot Engine (3.0) documentation in English

In detail: a variable will be preserved if the node holding it is not destroyed.
In Godot, there is a specific node in the scene tree which is treated as “the current scene”.

- SceneTreeRoot (Viewport)
	- Level1 <-- Current Scene
		- Player
		- Enemy
		- ...
	- Singleton1
	- Singleton2
	- ...

When you start the game, it will be an instance of the first scene to load.
When you use change_scene, that specific node will be destroyed and replaced by an instance of the next scene.
As you can see, “singleton” nodes are also in the tree, but will not be destroyed, which is why they will carry their state across scenes of your game.

Alternative approaches exist, such as taking out the Player node before changing scene, and add it back into the tree after the change is complete (assuming the script doing the change is not part of the destroyed scene).
Or, not use change_scene, and do the node swap on a child of the current scene instead (which makes the rest remain as well).

Thank you so much! Now I can finally complete my level select screen, I really appreciate the time you took to write this. Thank you

RowingNoob | 2020-03-10 03:55