Maintaining Global States with the Singleton Pattern
Games are complex dynamic systems with an infinite amount of different internal states and it is common to lose track of data when we do clean-ups from one major state to another. For instance, in most game engines, it’s a common practice, built into the engine, to get rid of all objects before adding new ones when we load a new level – in Godot’s case, a new scene. This causes some issues when we need to maintain some data or even the object itself processing.
If you played with background music in Godot, it’s likely that you noticed that it suddenly stops playing when you switch to another scene using get_tree().change_scene_to_file()
or get_tree().change_scene_to_packed()
. This is because Godot frees the current scene’s node hierarchy from the SceneTree
before adding the new scene’s node hierarchy. If you don’t manage to have your node outside of the current scene’s hierarchy...