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?
Create a tag on that GameObject like in my example “gameMusic”.
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);
}
}
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).
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);
}
}