I want music to continuously play even when the scene restarts

Hey guys, so I want the MusicManager game object to continuously play with new scenes loading in. The code below works, but does not archive what I wanted. There’s a game over state. And when the player is in that state, the scene restarts.

Let me firstly explain what’s going on inside the code: MusicManager detects another music manager, it destroys the one which is current inside “DontDestroyOnLoad” stage.

The code would work, but for some scenes, I added my own MusicManager to change the music playing in that scene, and because of this, whenever the scene restarts, the music also restarts…

public class MusicManager : MonoBehaviour
{
    static MusicManager instance;

    private void Awake()
    {
        CheckInstance();
    }

    void CheckInstance()
    {
        // This gets check with every MusicManager
        // UNLIKE LOCALS, THE GLOBAL INSTANCE WILL ONLY CHECK ONCE ON AWAKE

        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(instance.gameObject);
        }
        else
        {
            Destroy(instance.gameObject);
        }
    }
}

Any advice are appreciated! Thanks in advance.

I think it’s because you’re checking if there is already a music manager, and then if there is, you’re destroying it - but that defeats the point of DontDestroyOnLoad :stuck_out_tongue: - because you are destroying it on load.

You want to check if there is already a music manager, and if there is, do nothing. If not, only then should you create a new one.

When you’re destroying the old one and creating a new one, the music is restarting because it’s a newly created manager in that scene

EDIT: Added code below - in your else statement, you should be destroying the gameobject, rather than the instance. Destroying the instance was destroying the one you had preserved, rather than the new object that had just awoken.

if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(instance.gameObject);
        }
        else
        {
            Destroy(gameObject);
        }