0
0
Unityframework~15 mins

DontDestroyOnLoad usage in Unity - Deep Dive

Choose your learning style9 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.