Search code examples
c#unity-game-enginebackgroundplayback

How to have an object in Unity 3D that stays in scenes and does not recreate


I’m trying to find a good way to play background music in Unity 3D. I want the music to keep playing consistently through scene loads. Don’t Destroy on load is fine and works, but every time I load the same scene, it makes another music game object because the scene itself has the game object in it. How can I solve my problem? I am a “beginner” (kind of), so I would like code I can understand.


Solution

  • With help from a question on the unity forum, I think I have solved my problem. The link to the question is here...

    https://answers.unity.com/questions/982403/how-to-not-duplicate-game-objects-on-dontdestroyon.html

    The Best Answer is the one I’m using.

    The code is this...

    private static Player playerInstance;
    
    void Awake(){
        DontDestroyOnLoad(this);
    
        if (playerInstance == null) {
            playerInstance = this;
        } else {
            Destroy(gameObject); // Used Destroy instead of DestroyObject
        }
    }