how to keep audio from restaring on scene reloading in unity

im making a game that uses alot of scenes and i want to add background music but when the scene reloads/switches the audio stops or restarts. is there a way to fix this?

I haven’t tried this myself yet, but I imagine you could call DontDestroyOnLoad(yourAudioSourceGameObject) before unloading the scene to keep it from being disposed. You might also want to keep a static reference to your audio source somewhere so you’ll be able to adjust volume, stop playback, dispose it yourself later or whatever else easily from any scene.

1 Like

That works as long as you can’t go back to the original scene that had the object with the audio. If it does, you’ll have two unless you check for whether it exists. To avoid that you need to use a singleton pattern or run a loading scene (that the player can’t go back to).

1 Like

@seejayjames is correct - another way to avoid that would be when you would instantiate your audio source, first check if your static reference is null. If it is, then instantiate it and set the reference. Otherwise, you would skip the instantiation because it already exists.

1 Like

This problem came up a lot in a course I taught, with audio for menu screens versus game audio, so there was some fiddling needed to avoid duplicates. Some students wanted one continuous audio for all the menu scenes, others wanted it to restart when you landed back on the intro page, etc.

A loading scene is also good, you can init things like the audio as well as anything else you want. The only caveat is when you’re developing, you have to save whatever scene you’re on, switch to the init scene, and run that for everything to work correctly. That said, you can put a script in each scene that checks if the init scene has been run (just a bool), and if not, switch to it and pass the scene you want to load after it’s run. A bit janky but does have some advantages, because the player can’t ever get back to the loading scene during gameplay.

1 Like

do you mind if you could make a example script so i can understand it better?

Don’t really have the time, but you should be able to find stuff on this exact issue pretty easily, it comes up with audio in particular with changing scenes. So you can use the singleton idea, which is kind of what @adamgolden said—you have just one object/script that deals with the audio, with DontDestroyOnLoad so it persists (and keeps playing). When you load a scene, check to see if it exists. It might never be an issue, just depends on how you allow the player to navigate between scenes.

I might be using the “singleton” terminology wrong here, not 100% sure :wink:

1 Like