How to play same game music through different levels.

Hi guys,

I have been stuck on reaching an effective method for creating an instance of game music in the main menu and in the levels.
What I hope to achieve is one piece of music playing through the different menu scenes and then another piece of music for the game.

The problem I have is when using ‘DontDestroyOnLoad’ I get music spawning twice!

Any help on how to make a music manager script would be very much appreciated thank you.

The problem is that the music playing object exists in the scene to begin with, so when the scene is loaded again, a new instance is loaded as well. Since you can’t undo DontDestroyOnLoad() that means you have to either load it after the scene is loaded, provided there is no such object in existence already, or destroy the excess one after the scene was loaded.

I personally use this script here to manage all those objects, and tag them “DontDestroy”. This script also manages applying the DontDestroyOnLoad() attribute to these objects so I don’t have to put it in each individual script I want to keep around.

using System.Collections.Generic;
using UnityEngine;

public class HouseKeeping : MonoBehaviour
	private void Awake()
		//make sure the game keeps running even if the application is out of focus so communication to the server/client continues
		Application.runInBackground = true;


	/// <summary>
	/// Make sure we have only one instance of each utility
	/// </summary>
	private void CleanUtilities()
		//Get all the utilities in current scene
		var utilities = GameObject.FindGameObjectsWithTag(transform.tag);

		//Will contain unique names of utilities
		var uniqueUtilities = new LinkedList<string>();

		if (utilities == null) return;

		for (int i = (utilities.Length - 1); i >= 0; i--)
			//Search if we already have this kind of utility and destroy it
			if (uniqueUtilities.Contains(utilities*.name))*

_ Destroy(utilities*);*_

* //If not add it to our unique list and apply DontDestroyOnLoad to it*
* else*
* {*
_ uniqueUtilities.AddLast(utilities*.name);

You can use the singleton pattern. There is a lot of forum posts and questions in Unity Answers regarding this topic.

For example: Singletons with coroutines? - Questions & Answers - Unity Discussions