0
0
Unityframework~8 mins

DontDestroyOnLoad usage in Unity - Performance & Optimization

Choose your learning style9 modes available
Performance: DontDestroyOnLoad usage
MEDIUM IMPACT
This affects how game objects persist across scene loads, impacting memory usage and scene load performance.
Keeping a game manager object alive across multiple scene loads
Unity
void Awake() {
  if (FindObjectsOfType<GameManager>().Length > 1) {
    Destroy(this.gameObject);
    return;
  }
  DontDestroyOnLoad(this.gameObject);
}
Prevents duplicate objects by destroying extras, keeping memory and CPU usage stable.
📈 Performance GainMemory usage remains constant; scene load times stay consistent
Keeping a game manager object alive across multiple scene loads
Unity
void Awake() {
  DontDestroyOnLoad(this.gameObject);
}

// No check for duplicates, so multiple instances accumulate after scene reloads
Multiple instances of the same object accumulate, increasing memory and CPU usage unnecessarily.
📉 Performance CostIncreases memory usage linearly with each scene load; can cause slow scene transitions
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
DontDestroyOnLoad without duplicate checkN/AN/AN/A[X] Bad
DontDestroyOnLoad with duplicate checkN/AN/AN/A[OK] Good
Rendering Pipeline
DontDestroyOnLoad affects the scene management phase by keeping objects alive beyond scene unloads, which means the rendering pipeline must handle these persistent objects each frame.
Scene Management
Memory Management
Rendering
⚠️ BottleneckMemory Management due to accumulating objects if not handled properly
Optimization Tips
1Always check for existing instances before calling DontDestroyOnLoad.
2Destroy duplicate persistent objects to avoid memory leaks.
3Use Unity Profiler to monitor memory and object counts during scene loads.
Performance Quiz - 3 Questions
Test your performance knowledge
What is a common performance issue when using DontDestroyOnLoad without safeguards?
AMultiple copies of the same object accumulate, increasing memory use
BThe object is destroyed too early causing errors
CThe object causes the scene to reload infinitely
DThe object disables rendering of other objects
DevTools: Profiler
How to check: Open Unity Profiler, load scenes multiple times, and watch memory usage and object count in Hierarchy.
What to look for: Increasing memory or growing number of persistent objects indicates missing duplicate checks.