How to have an object in Unity 3D that stays in scenes and does not recreate

Viewed 1370

I’m trying to find a good way to play background music in Unity 3D. I want the music to keep playing consistently through scene loads. Don’t Destroy on load is fine and works, but every time I load the same scene, it makes another music game object because the scene itself has the game object in it. How can I solve my problem? I am a “beginner” (kind of), so I would like code I can understand.

3 Answers

I'd hands down recommend starting with an Asset like 'EazySoundManagerDemo'. It needs a little refactoring and refinement (ie it uses 3 arrays of audios with 3 sets of accessibility functions instead of one set with an AudioPurpose enum to increase code-reuse).

It does however solve the basic problem you have and is a good intro to using an audio manager / layer instead of simply playing audio directly from your GameObjects. Give that a shot, learn from it and then adapt it or create your own audio management layer.

Good Luck!

I recommend creating an audioSource object, then creating an script for this object and on the awake function do this:

void Awake() {
    DontDestroyOnLoad(this.gameObject);
}

This will make the background music to keep playing between scenes. For more information you could use Unity's documentation about this function.

Related