Background Music - loops without restarting on player death (scene reset), but changes when scene moves to different scene?

Essentially if my player dies, it loads the same scene. The music then also loads again. If you use DontDestroyOnLoad() it will duplicate itself. I know there are solutions to this, but the problem is none of them allow me to change the music again once the level is beaten and the new one loads.

Any suggestions? I’m really new to programming and Unity!

Thanks!

AH HA!

public class MusicController : MonoBehaviour {

	public GameObject BGMPLAYER;

	void Start() {

		BGMPLAYER = GameObject.Find ("MUSIC");
		if (BGMPLAYER == null) {
			BGMPLAYER = this.gameObject;
			BGMPLAYER.name = "MUSIC";
			DontDestroyOnLoad (BGMPLAYER);
		} else {
			if (this.gameObject.name != "MUSIC") {
				Destroy (this.gameObject);
			}
		}
	}
	
	// Update is called once per frame
	void Update () {

}

}

I was using this from another answer forum. However, it would not work with loading new scenes…

In my game, you have to grab a special object to proceed to the next scene. SO, I made a few changes to that script to check if the BGMPLAYER game object is named “MUSIC” or not…then both situations destroy that audio object when collision is made with the level changing item!

public class nextLevel : MonoBehaviour {
	public GameObject BGMPLAYER;
	private GameObject MUSIC;
	void Start(){

	
	}
	// Update is called once per frame
	void Update () {
			

		}

	void OnCollisionEnter2D (Collision2D col){
		if (col.gameObject.tag == "endball") {
			BGMPLAYER = GameObject.Find ("MUSIC");
			if (BGMPLAYER.name == "MUSIC"){
				Destroy (BGMPLAYER);
			}
			Destroy (BGMPLAYER);
			SceneManager.LoadScene (SceneManager.GetActiveScene().buildIndex +1);
		}
	} 
}

AND IT WORKS! :smiley:

Tho im not sure if that second instance of "Destroy(BGMPLAYER) is necessary.