What if your game's music and score could magically survive every scene change without extra code?
Why DontDestroyOnLoad usage in Unity? - Purpose & Use Cases
Imagine you are making a game where the player's score or music should keep playing even when moving between different game levels or scenes.
Without special handling, every time you load a new scene, all objects from the previous scene disappear, and you lose the score or music.
Manually copying data or restarting music every time a new scene loads is slow and error-prone.
You might forget to save or restore something, causing bugs or a bad player experience.
DontDestroyOnLoad lets you mark important game objects so they stay alive and keep working across scene changes automatically.
This means your music keeps playing and your score stays intact without extra work.
SceneManager.LoadScene("Level2"); // music stops, score resetsDontDestroyOnLoad(gameObject); // music and score persist across scenesYou can create smooth, continuous gameplay experiences where key objects survive scene changes effortlessly.
In a game, the background music player object uses DontDestroyOnLoad so the music never stops even when the player moves from the main menu to the game level.
Scene changes normally destroy all objects, losing data or effects.
DontDestroyOnLoad keeps marked objects alive across scenes.
This makes managing persistent data or effects easy and reliable.