If you call the don't destroy on load function on your music player, then it won't be destroyed when you switch between scenes.
The only problem is that if you return to the scene where you started the music you will have two music players. The easy way to fix that is to do a check to see if your music player already exists when you load into that scene.
The below code is untested and surely has mistakes in it, but I tried to comment what I was doing so you could sort of get the idea of the logic involved. You would put this script on your music player. NOTE: The music player would need to be called something other than MUSIC at first for this to work.
EDIT: I just had to actually use this code in my own project and I found some bugs in it so I'm re-posting it here in case someone sees this and is still having the same problem of duplicate music players.
public GameObject musicPlayer;
void Awake() {
//When the scene loads it checks if there is an object called "MUSIC".
musicPlayer = GameObject.Find("MUSIC");
if(musicPlayer==null)
{
//If this object does not exist then it does the following:
//1. Sets the object this script is attached to as the music player
musicPlayer = this.gameObject;
//2. Renames THIS object to "MUSIC" for next time
musicPlayer.name = "MUSIC";
//3. Tells THIS object not to die when changing scenes.
DontDestroyOnLoad(musicPlayer);
}else{
if(this.gameObject.name!="MUSIC"){
//If there WAS an object in the scene called "MUSIC" (because we have come back to
//the scene where the music was started) then it just tells this object to
//destroy itself if this is not the original
Destroy(this.gameObject);
}
}
}
↧