Background music is one of the most immersive elements of a game. It dictates the mood and pace of a level or even of the whole play through, but there’s a common mistake that may happen when we are working with background music in most game engines. When transitioning between game scenes the music gets cut and is common that it restart from beginning, completely breaking the immersion.
One of the simplest ways we can solve this problem is by using a Singleton responsible to play the background music. Since singletons are accessible globally and there can only be a single instance of them, they can be used to maintain the music playing while all other objects are freed from memory between scene transitions.
The BackgroundMusic Singleton
In Godot Engine we can play audio stream files through an AudioStreamPlayer Node. We are going to use it and rename it as BackgroundMusic, alternatively you can already drag your music file to the Stream property slot and toggle on the Autoplay flag.
With that we just need to turn this scene into an Autoload. In Godot Engine an Autoload is a scene that is loaded automatically and instanced aside from the main scene, allowing it to be apart from changes in the SceneTree structure caused by the
get_tree().change_scene_to methods. In other words, when calling one of those methods an Autoload stays in the SceneTree processing normally.
Let’s turn our BackgroundMusic into an Autoload now. In the Project > Project Settings > Autoload browse the BackgroundMusic file to set it as an Autoload.
Now whenever you test your game the BackgroundMusic will instance alongside the scene you are testing and won’t be removed unless you manually
queue_free it and with that our BackgroundMusic can keep playing throughout scenes.
Our tutorials are the result of careful teamwork to ensure we produce high quality content. The following team members worked on this one: