DontDestroyOnLoad problem

Hi I’m trying to have a song start in Scene 1 and then continue through to Scene 2. But if Scene 3 happens, I want the audio to stop. I have Scene 1 to Scene 2 worked out. But for some reason I can’t figure out how to stop the audio at Scene 3.

With the code below, I have the game object in Scene 1 not being destroyed on load anywhere. And that LOST bool in the Update function comes from Scene 3. If it is true, then the Audio Source of the game object in Scene 1 should be false. But it just doesn’t work.

Any help would be great. Thanks!

 void Start()
{
	GameObject.DontDestroyOnLoad (gameObject);

	loseCollider = GameObject.FindGameObjectWithTag ("LoseCollider");
}

void Update()
{
	

	if (loseCollider.GetComponent<LoseTriggerScript> ().LOST == true) 
	{
		this.GetComponent<AudioSource>().enabled = false;
	}
}

That’s because Start is called only once for the GameObject, not per scene. This means by the time you’re at scene 3, loseCollider is null. This kind of poll approach is not a very good idea either.

You can do the following:

the relevant parts are:

void OnEnable()
    {
        SceneManager.sceneLoaded += OnSceneLoaded;
    }

    void OnSceneLoaded(Scene scene, LoadSceneMode mode)
    {
        // check scene.buildIndex or scene.name
        //Whatever should be disabled
    }

With any scene loaded, you get a call to OnSceneLoaded where you can check for the scene and then execute your code.
Don’t forget to -= the OnSceneLoaded in OnDisable()

SceneManager.sceneLoaded is an event. events avoid polling.