Game Development
DontDestroyOnLoad
Learn to keep objects across scene loads with DontDestroyOnLoad.
What is DontDestroyOnLoad?
By default, transitioning to a new scene in Single mode destroys all GameObjects from the prior scene. Calling DontDestroyOnLoad(gameObject); exempts the target object from this purge, allowing it to persist across scene changes.
void Awake() {
// This object survives scene transitions
DontDestroyOnLoad(gameObject);
}
Background music players or player profile managers maintain uninterrupted execution through this call.
Singleton Pattern and Persistent Managers
Persistent objects can inadvertently duplicate if the player revisits an earlier scene. Implementing the Singleton design pattern ensures only one instance survives in memory.
public static GameManager Instance;
void Awake() {
if (Instance == null) {
Instance = this;
DontDestroyOnLoad(gameObject);
} else {
Destroy(gameObject); // Destroy redundant clone
}
}
This guarantees centralized and error-free game state management throughout the entire application.
Exercise Print manager and persistence state
Assign "GameManager" to managerName and "DontDestroyOnLoad" to status. Print Manager: GameManager | Status: DontDestroyOnLoad to the console.
Show example solution
using System;
class Program
{
static void Main()
{
string managerName = "GameManager";
string status = "DontDestroyOnLoad";
Console.WriteLine("Manager: " + managerName + " | Status: " + status);
}
}
Test yourself
-
Which function is called so a GameObject is not destroyed during a scene transition and persists into the next scene?
- DestroyImmediate(gameObject);
- SceneManager.KeepAlive(gameObject);
- DontDestroyOnLoad(gameObject);
- Object.PersistForever(gameObject);
Show answer
DontDestroyOnLoad(gameObject); — DontDestroyOnLoad() is the built-in Unity method protecting the target object from automatic cleanup on scene changes.
-
Safeguard object from scene cleanup
____(gameObject);
Show answer
DontDestroyOnLoad(gameObject);
-
Persistence concepts
- DontDestroyOnLoad
- Protects object from scene cleanup
- Singleton
- Pattern with only one instance allowed
- GameManager
- Carries game data and flow across scenes
- Persist
- Object stays in memory across scenes
Next lesson: Async loading