Bird
Raised Fist0
Unityframework~15 mins

DontDestroyOnLoad usage in Unity - Deep Dive

Choose your learning style10 modes available
Overview - DontDestroyOnLoad usage
What is it?
DontDestroyOnLoad is a Unity function that keeps a game object alive when switching between scenes. Normally, when you load a new scene, all objects in the previous scene are removed. Using DontDestroyOnLoad stops this from happening for specific objects. This helps keep important data or managers running continuously.
Why it matters
Without DontDestroyOnLoad, you would lose all objects and their data every time you change scenes. This means things like player stats, music players, or game managers would reset or disappear, breaking the game experience. DontDestroyOnLoad solves this by preserving objects, making games feel smooth and consistent.
Where it fits
Before learning DontDestroyOnLoad, you should understand Unity scenes and how objects are created and destroyed. After this, you can learn about singleton patterns and scene management to organize persistent objects better.
Mental Model
Core Idea
DontDestroyOnLoad tells Unity to keep an object alive across scene changes instead of deleting it.
Think of it like...
It's like carrying your favorite book in your backpack when moving to a new house, so you don't have to start reading from scratch every time you move.
Scene 1 ──> Load Scene 2
  │                 │
  ├─ Object A (destroyed)
  └─ Object B (DontDestroyOnLoad) ──> stays alive in Scene 2
Build-Up - 6 Steps
1
FoundationUnderstanding Scene Loading Basics
🤔
Concept: Learn how Unity loads and unloads scenes and what happens to game objects during this process.
In Unity, when you load a new scene, all objects from the previous scene are removed by default. This means any game object you created in the first scene will be destroyed unless you tell Unity otherwise.
Result
Objects not marked to persist are destroyed on scene load.
Knowing that scene loading clears objects helps you understand why some data or objects disappear unexpectedly.
2
FoundationWhat Does DontDestroyOnLoad Do?
🤔
Concept: Introduce the DontDestroyOnLoad function and its basic effect on game objects.
DontDestroyOnLoad is a Unity method you call on a game object to make it survive scene changes. When you call DontDestroyOnLoad(gameObject), Unity keeps that object alive even when loading a new scene.
Result
The marked object remains active and unchanged across scenes.
Understanding this function is key to managing persistent game data or managers.
3
IntermediateApplying DontDestroyOnLoad in Code
🤔Before reading on: Do you think calling DontDestroyOnLoad on a child object keeps the whole parent hierarchy alive? Commit to your answer.
Concept: Learn how to correctly use DontDestroyOnLoad in scripts and understand its scope.
You usually call DontDestroyOnLoad in a script attached to the object you want to keep. For example: void Awake() { DontDestroyOnLoad(gameObject); } Note: Calling DontDestroyOnLoad on a child object keeps only that child alive, not the entire parent hierarchy.
Result
The specific game object survives scene loads, but unrelated objects do not.
Knowing the scope of DontDestroyOnLoad prevents confusion about which objects persist.
4
IntermediateCommon Use Cases for DontDestroyOnLoad
🤔Before reading on: Do you think DontDestroyOnLoad is suitable for all game objects? Commit to your answer.
Concept: Explore typical scenarios where DontDestroyOnLoad is useful and when it is not.
Common uses include: - Music players that keep playing across scenes - Game managers that hold player data - UI elements that should persist However, not all objects should use it, especially those tied to a single scene's logic.
Result
You understand when to apply DontDestroyOnLoad effectively.
Recognizing appropriate use cases helps avoid clutter and bugs from unnecessary persistent objects.
5
AdvancedManaging Multiple Persistent Objects
🤔Before reading on: Do you think multiple objects marked DontDestroyOnLoad can cause duplicates after scene reloads? Commit to your answer.
Concept: Learn how to handle duplicates and organize persistent objects safely.
If you load a scene that creates the same persistent object again, you can get duplicates. To avoid this, use singleton patterns or checks: void Awake() { if (Instance == null) { Instance = this; DontDestroyOnLoad(gameObject); } else { Destroy(gameObject); } } This ensures only one instance survives.
Result
You prevent duplicate persistent objects and keep your game stable.
Understanding object lifecycle across scenes is crucial for clean, bug-free persistence.
6
ExpertInternal Scene Management and DontDestroyOnLoad
🤔Before reading on: Do you think DontDestroyOnLoad objects are part of the new scene's hierarchy? Commit to your answer.
Concept: Discover how Unity internally manages DontDestroyOnLoad objects separate from scene hierarchies.
Unity moves DontDestroyOnLoad objects to a special internal scene called 'DontDestroyOnLoad' scene. This scene is never unloaded, so these objects stay alive. They are not part of any loaded scene's hierarchy, which means they don't get destroyed but also don't appear in the new scene's root hierarchy.
Result
You understand why these objects persist and how Unity isolates them.
Knowing this internal detail explains why some scene operations don't affect persistent objects.
Under the Hood
When you call DontDestroyOnLoad on a game object, Unity removes it from the current scene's hierarchy and places it into a special internal scene that is never unloaded. This means the object is excluded from the normal scene destruction process. Unity keeps a reference to this object separately, so it remains active and accessible across all scene loads.
Why designed this way?
Unity needed a way to keep important objects alive without complicating the scene unloading process. By isolating persistent objects in a special scene, Unity avoids mixing persistent and temporary objects, simplifying memory management and scene transitions. Alternatives like manually copying objects between scenes would be error-prone and inefficient.
┌───────────────────────────────┐
│ Scene 1                      │
│ ┌───────────────┐            │
│ │ Object A      │            │
│ └───────────────┘            │
│ ┌───────────────┐            │
│ │ Object B      │            │
│ └───────────────┘            │
└─────────────┬─────────────────┘
              │ DontDestroyOnLoad called on Object B
              ▼
┌───────────────────────────────┐
│ DontDestroyOnLoad Scene        │
│ ┌───────────────┐            │
│ │ Object B      │            │
│ └───────────────┘            │
└───────────────────────────────┘

┌───────────────────────────────┐
│ Scene 2                      │
│ ┌───────────────┐            │
│ │ Object C      │            │
│ └───────────────┘            │
└───────────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does DontDestroyOnLoad keep the entire parent object hierarchy alive? Commit to yes or no.
Common Belief:Calling DontDestroyOnLoad on a child object keeps its whole parent hierarchy alive.
Tap to reveal reality
Reality:DontDestroyOnLoad only preserves the specific game object it is called on, not its parents or siblings.
Why it matters:Assuming the whole hierarchy persists can cause unexpected object destruction and bugs.
Quick: Can you use DontDestroyOnLoad on every object without issues? Commit to yes or no.
Common Belief:You can safely mark any object with DontDestroyOnLoad to keep it alive.
Tap to reveal reality
Reality:Using DontDestroyOnLoad on many or inappropriate objects leads to clutter, memory leaks, and hard-to-debug issues.
Why it matters:Misusing persistence causes performance problems and unexpected behavior.
Quick: Are DontDestroyOnLoad objects part of the new scene's hierarchy? Commit to yes or no.
Common Belief:Persistent objects appear in the new scene's hierarchy after loading.
Tap to reveal reality
Reality:They are moved to a special internal scene and do not appear in the new scene's hierarchy.
Why it matters:Expecting them in the scene hierarchy can confuse debugging and scene organization.
Quick: Does DontDestroyOnLoad automatically prevent duplicates after scene reloads? Commit to yes or no.
Common Belief:Calling DontDestroyOnLoad ensures only one instance exists across scenes.
Tap to reveal reality
Reality:Without manual checks, loading scenes that create the same object causes duplicates.
Why it matters:Duplicates can cause logic errors, crashes, or unexpected game states.
Expert Zone
1
DontDestroyOnLoad objects are stored in a hidden internal scene, which means they don't receive scene-specific callbacks like OnSceneLoaded.
2
Persistent objects can cause memory leaks if not properly destroyed when no longer needed, especially in long play sessions.
3
Using DontDestroyOnLoad with singletons requires careful lifecycle management to avoid stale references or unintended persistence.
When NOT to use
DontDestroyOnLoad is not suitable for objects tightly coupled to a single scene's logic or visuals. Instead, use scene-specific initialization or pass data via scriptable objects or scene parameters. For temporary data persistence, consider PlayerPrefs or external storage.
Production Patterns
In production, DontDestroyOnLoad is often combined with singleton patterns to create global managers (e.g., AudioManager, GameManager). Developers add checks in Awake to prevent duplicates and ensure only one instance persists. It's also common to organize persistent objects under a dedicated root object for clarity.
Connections
Singleton Pattern
Often combined with DontDestroyOnLoad to ensure a single persistent instance.
Understanding how DontDestroyOnLoad supports singletons helps manage global game state effectively.
Scene Management
DontDestroyOnLoad affects how scenes load and unload objects.
Knowing scene lifecycle clarifies when and why to use DontDestroyOnLoad.
Memory Management in Operating Systems
Both manage resources by deciding what to keep or discard during context switches.
Seeing DontDestroyOnLoad like OS memory management helps grasp persistence and cleanup tradeoffs.
Common Pitfalls
#1Creating multiple persistent objects causing duplicates.
Wrong approach:void Awake() { DontDestroyOnLoad(gameObject); } // No check for existing instances
Correct approach:void Awake() { if (Instance == null) { Instance = this; DontDestroyOnLoad(gameObject); } else { Destroy(gameObject); } }
Root cause:Not guarding against multiple instances leads to duplicate persistent objects.
#2Calling DontDestroyOnLoad on child objects expecting parents to persist.
Wrong approach:void Awake() { DontDestroyOnLoad(transform.GetChild(0).gameObject); }
Correct approach:void Awake() { DontDestroyOnLoad(gameObject); }
Root cause:Misunderstanding that only the called object persists, not its parents.
#3Marking all objects as DontDestroyOnLoad causing clutter and memory issues.
Wrong approach:foreach (var obj in allObjects) { DontDestroyOnLoad(obj); }
Correct approach:Only mark essential global managers or data holders with DontDestroyOnLoad.
Root cause:Lack of selective persistence leads to performance and maintenance problems.
Key Takeaways
DontDestroyOnLoad keeps specific game objects alive across scene changes by moving them to a special internal scene.
It is essential for preserving global data like player stats, music, or managers during gameplay.
Proper use requires guarding against duplicates and understanding that only the marked object persists, not its parents.
Misusing DontDestroyOnLoad can cause memory leaks, clutter, and bugs, so use it selectively and with patterns like singletons.
Knowing how Unity manages persistent objects internally helps debug and design better scene transitions.

Practice

(1/5)
1. What is the main purpose of using DontDestroyOnLoad in Unity?
easy
A. To pause the game during scene loading
B. To destroy a GameObject immediately
C. To load a new scene asynchronously
D. To keep a GameObject alive when switching scenes

Solution

  1. Step 1: Understand what DontDestroyOnLoad does

    This method prevents a GameObject from being destroyed when a new scene loads.
  2. Step 2: Identify the purpose in scene management

    It keeps important objects like music players or managers alive across scenes.
  3. Final Answer:

    To keep a GameObject alive when switching scenes -> Option D
  4. Quick Check:

    DontDestroyOnLoad keeps objects alive = A [OK]
Hint: Remember: DontDestroyOnLoad means object stays between scenes [OK]
Common Mistakes:
  • Thinking it destroys objects instead of preserving them
  • Confusing it with scene loading functions
  • Assuming it pauses the game
2. Which of the following is the correct way to use DontDestroyOnLoad in a Unity script?
easy
A. DontDestroyOnLoad(this);
B. DontDestroyOnLoad(Scene);
C. DontDestroyOnLoad(gameObject);
D. DontDestroyOnLoad(SceneManager);

Solution

  1. Step 1: Identify the correct parameter for DontDestroyOnLoad

    The method requires a GameObject to keep alive, usually referenced as gameObject in scripts.
  2. Step 2: Check each option

    DontDestroyOnLoad(gameObject); uses gameObject, which is correct. DontDestroyOnLoad(this); uses this (the script), which is incorrect. Options B and C use unrelated types.
  3. Final Answer:

    DontDestroyOnLoad(gameObject); -> Option C
  4. Quick Check:

    Use gameObject with DontDestroyOnLoad = D [OK]
Hint: Use gameObject, not this or Scene, with DontDestroyOnLoad [OK]
Common Mistakes:
  • Passing 'this' instead of 'gameObject'
  • Trying to pass Scene or SceneManager objects
  • Calling DontDestroyOnLoad without parameters
3. Consider this Unity C# script attached to a GameObject:
void Awake() {
    DontDestroyOnLoad(gameObject);
}

void Start() {
    Debug.Log("Object alive");
}
What will happen when the scene changes?
medium
A. The GameObject will persist and "Object alive" will print once
B. The GameObject will be destroyed and "Object alive" will not print again
C. The GameObject will persist and "Object alive" will print every scene load
D. The GameObject will be duplicated on each scene load

Solution

  1. Step 1: Understand when Awake and Start run

    Awake runs once when the object is created. Start runs once after Awake. Both run only once per object lifetime.
  2. Step 2: Effect of DontDestroyOnLoad on scene change

    The GameObject is kept alive across scenes, so Awake and Start do not run again on scene load.
  3. Final Answer:

    The GameObject will persist and "Object alive" will print once -> Option A
  4. Quick Check:

    DontDestroyOnLoad keeps object alive, Awake/Start run once = A [OK]
Hint: Awake/Start run once; object stays alive with DontDestroyOnLoad [OK]
Common Mistakes:
  • Thinking Start runs on every scene load
  • Assuming object duplicates on scene change
  • Believing object is destroyed on scene change
4. You wrote this code in a Unity script:
void Start() {
    DontDestroyOnLoad(this);
}
What is the problem and how to fix it?
medium
A. Error: DontDestroyOnLoad must be called in Awake, not Start
B. Error: 'this' is not a GameObject; fix by using DontDestroyOnLoad(gameObject);
C. No problem; code works fine as is
D. Error: DontDestroyOnLoad requires a Scene parameter

Solution

  1. Step 1: Identify the parameter type for DontDestroyOnLoad

    DontDestroyOnLoad requires a GameObject, but 'this' refers to the script instance, not the GameObject.
  2. Step 2: Correct the parameter

    Use gameObject to pass the GameObject the script is attached to.
  3. Final Answer:

    Error: 'this' is not a GameObject; fix by using DontDestroyOnLoad(gameObject); -> Option B
  4. Quick Check:

    DontDestroyOnLoad needs gameObject, not this = C [OK]
Hint: Pass gameObject, not this, to DontDestroyOnLoad [OK]
Common Mistakes:
  • Passing 'this' instead of 'gameObject'
  • Thinking DontDestroyOnLoad must be in Awake only
  • Passing wrong types like Scene or SceneManager
5. You want to keep a music player GameObject alive across scenes but avoid duplicates if the scene reloads. Which code snippet correctly implements this using DontDestroyOnLoad?
hard
A. void Awake() { if (FindObjectsOfType<MusicPlayer>().Length > 1) { Destroy(gameObject); } else { DontDestroyOnLoad(gameObject); } }
B. void Awake() { DontDestroyOnLoad(gameObject); }
C. void Start() { Destroy(gameObject); DontDestroyOnLoad(gameObject); }
D. void Awake() { Destroy(gameObject); }

Solution

  1. Step 1: Understand the problem of duplicates

    Using DontDestroyOnLoad alone keeps the object alive, but reloading the scene creates duplicates.
  2. Step 2: Use a check to destroy duplicates

    void Awake() { if (FindObjectsOfType<MusicPlayer>().Length > 1) { Destroy(gameObject); } else { DontDestroyOnLoad(gameObject); } } checks if more than one MusicPlayer exists and destroys the extra one, preventing duplicates.
  3. Step 3: Verify other options

    void Awake() { DontDestroyOnLoad(gameObject); } keeps duplicates. void Start() { Destroy(gameObject); DontDestroyOnLoad(gameObject); } destroys then calls DontDestroyOnLoad (wrong order). void Awake() { Destroy(gameObject); } destroys always.
  4. Final Answer:

    void Awake() { if (FindObjectsOfType<MusicPlayer>().Length > 1) { Destroy(gameObject); } else { DontDestroyOnLoad(gameObject); } } -> Option A
  5. Quick Check:

    Check duplicates before DontDestroyOnLoad to avoid duplicates = B [OK]
Hint: Check existing objects before DontDestroyOnLoad to prevent duplicates [OK]
Common Mistakes:
  • Not checking for duplicates causing multiple music players
  • Destroying object before calling DontDestroyOnLoad
  • Calling DontDestroyOnLoad without duplicate check
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard