I am trying to keep a song playing in the background from the moment the player loads the game.
The script is keeping the object to the next scene and I can see my music object there but the musics stops, if I click the back button then the music continues but only when I am in the main menu. Any ideas what I’m doing wrong?
C#:
private void Awake()
{
GameObject[ ] objs = GameObject.FindGameObjectsWithTag(“music”);
if (objs.Length > 1)
{
Destroy(this.gameObject);
}
DontDestroyOnLoad(this.gameObject);
}
Where is the code where you start playing the music (Is it a “play on wake” AudioSource)? What about the code where you are changing scenes? The answer probably lies in one of those scripts.
Adding to Praetor’s questions above, you are ONLY marking the GameObject hosting the above script not to destroy. The sound source itself, if it is anywhere else (which is implied by your finding ALL of them!), has not yet been marked, at least by this script.
If you really want to keep this simple, just make a single script called DontDestroyMe.cs to go on each sound source:
using UnityEngine;
public class DontDestroyMe : MonoBehaviour
{
void Awake()
{
DontDestroyOnLoad( transform.root.gameObject);
}
}
Put all those in a scene that you ONLY use once and then they will never go away. Don’t put it in your first scene if you ever plan on going back there because now you’ll have two of them… or three of them, etc.
If you want finer-grained control, look into something called a UnitySingleton, which has been implemented in about 57,000 different slightly-variant varieties out there and can be googled for.
1 Like