Keep audio playing even though I reset the scene

Hey Unitarians!

I have a simple game, and I have it that when you die, you have two options - to restart, or to go to the main menu. The main menu works fine and so does the restart. The way I do the restart is with a simple Application.LoadLevel (Application.loadedLevelName);. The problem is that the music gets reset.

Is there anyway to keep the music playing once I reset as if the scene wasn’t reloaded?

Thanks,
Aman Jha

  1. Create a GameObject with only the audioSource.

  2. Create a tag on that GameObject like in my example “gameMusic”.

  3. Attach this script on it.

       using UnityEngine;
     using System.Collections;
     
     public class dontDestroyOnLoad : MonoBehaviour {
     
     	private GameObject[] music;
     
     	void Start(){
     		music = GameObject.FindGameObjectsWithTag ("gameMusic");
     		Destroy (music[1]);
     	}
     	
     	// Update is called once per frame
     	void Awake () {
     		DontDestroyOnLoad (transform.gameObject);
     	}
     }
    

I think this is what you’re looking for:

Just make sure in your script you don’t reinstantiate the audio and make sure you only play the audio if it’s not already playing, otherwise you’ll restart it even if you don’t destroy the object from the previous loaded scene.

You can use DontDestroyOnLoad on the object holding the audio source (make sure there aren’t other things on the object that will cause issues if carried over).

Also keep in mind that if that object is placed in the scene manually, then you will need to destroy the newly spawned one on reload (otherwise every time you restart you will get an additional copy playing).

public class MusicPlayer : MonoBehaviour {

    static MusicPlayer instance = null;

    void Awake()
    {
        if (instance != null)
        {
            Destroy(gameObject);
        }
        else
        {
            instance = this;
            GameObject.DontDestroyOnLoad(gameObject);
        }
    }
}

Thanks @Lesovoy and @W4rf4c3, below is what worked for me (Inside GameController.cs of a GameController object in the reloaded scene):

public AudioSource bgm; // link this with a bgm prefab, add tag "BGM", loop, don't play on awake

void Awake() {
	GameObject currentBGM = GameObject.FindGameObjectWithTag ("BGM");
	if (currentBGM == null) {
		AudioSource spawned = Instantiate (bgm);
		spawned.Play ();
		DontDestroyOnLoad(spawned);
	}
}