0
0
Unityframework~5 mins

DontDestroyOnLoad usage in Unity

Choose your learning style9 modes available
Introduction

DontDestroyOnLoad keeps an object alive when you change scenes in a game. This helps keep important things like player data or music playing without restarting.

You want background music to keep playing when moving between game levels.
You need to keep player settings or scores without resetting after loading a new scene.
You have a game manager object that controls game state and should not be destroyed.
You want to keep a network connection alive across different scenes.
Syntax
Unity
DontDestroyOnLoad(gameObject);
Call this inside a script attached to the GameObject you want to keep.
Usually called in the Awake() or Start() method.
Examples
Keeps the current GameObject alive when loading new scenes.
Unity
void Awake() {
    DontDestroyOnLoad(gameObject);
}
Another way to keep the GameObject alive, called in Start instead of Awake.
Unity
void Start() {
    DontDestroyOnLoad(this.gameObject);
}
Sample Program

This script keeps the MusicPlayer object alive when you change scenes. It prints a message when it starts.

Unity
using UnityEngine;

public class MusicPlayer : MonoBehaviour {
    void Awake() {
        DontDestroyOnLoad(gameObject);
    }

    void Start() {
        Debug.Log("Music player started and will not be destroyed on load.");
    }
}
OutputSuccess
Important Notes

If you call DontDestroyOnLoad on multiple copies of the same object, you may get duplicates after scene loads.

Use a singleton pattern to avoid duplicates when using DontDestroyOnLoad.

Summary

DontDestroyOnLoad keeps objects alive across scene changes.

Call it in Awake or Start on the GameObject you want to keep.

Useful for music, game managers, and persistent data.