I have background music running on start up of the game and want it to go uninterrupted when the player inevitably needs to reload the level. However, all I’ve been able to accomplish is not having the music starting up at all for some reason, or having the game object (sound source) duplicate itself continuously on each reload. Any help on this would be much appreciated.
In the first scene where the music starts add a game object with an audio srouce that you could name MusicObject.
Then add a script like this:
public class AudioScript:MonoBehaviour{
static AudioScript instance;
void Start(){
if(instance == null)
{
instance = this;
DontDestroyOnLoad(gameObject);
}
else if (instance != this)
{
Destroy(gameObject);
}
}
then later if you need to stop the music you can find the object by name and destroy it.
I would guess you know how to start and stop music.
EDIT: I added a singleton principle. First the static instance is null so the first instance is assigned to it. Next time, the static instance is not null but only the object that matches the instance will survive. So that should do it.
Well I have already found a different solution to the problem, but what was happening even with that code that you gave me is that when you reload the level it doesn’t destroy the game object, but instead, another one is created.