Make music persistent betweeen scenes?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By PugMasterPug

I have a AudioStreamPlayer playing music, how would I make the music persistent between scene changes?

:bust_in_silhouette: Reply From: eons

Make a scene/script and add make it autoload, that way it will be added to the root, independent of the current_scene.

:bust_in_silhouette: Reply From: anonymous

I think singletons are what you’re looking for. Singleton scenes and scripts will persist throughout the lifetime of your game, even when using change_scene(). You’ll also be able to access them globally from all of your other scripts. So in your case, you’ll want to have a music player scene set up as a singleton.

If you want to use your existing AudioStreamPlayer node, you can save it to a scene by right-clicking it and selecting “Save Branch as Scene” (you might want to give both the node and the scene a more identifiable name like “MusicPlayer”, just so you can keep track of it better.) Alternatively, you can just make a new scene with a single AudioStreamPlayer node and save it the usual way. Either way, be sure to delete the node from its original scene, so that there won’t be two music streams playing at the same time.

Now, to add the scene to your AutoLoad list. Navigate to Project > Project Settings > AutoLoad tab, then click the dotted button near the top-middle to open a file explorer. Double-click on your “MusicPlayer” scene, then click “Add” on the right-hand side. You should see your MusicPlayer scene added to the AutoLoad list, which means you should be good to go.

Don’t forget that you can access your singletons from any script, with just the name of the AutoLoad (for example, MusicPlayer.stop()).

Incredible explanation. Thank you very much!

Andy | 2020-02-02 16:57

This was very helpful! Thank you

93celeste | 2020-06-18 21:30

You are a hero to me for this knowledge. Good person!

Synectome | 2021-07-29 01:48