CodeBlanks Logo Icon CodeBlanks

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.

Practice Print manager and persistence state

Assign "GameManager" to managerName and "DontDestroyOnLoad" to status. Print Manager: GameManager | Status: DontDestroyOnLoad to the console.

Starter code

Player.cs
using System;

class Program
{
    static void Main()
    {
        // managerName ve status değerlerini tanımlayıp yazdır
    }
}

Sample solution

Player.cs
using System;

class Program
{
    static void Main()
    {
        string managerName = "GameManager";
        string status = "DontDestroyOnLoad";
        Console.WriteLine("Manager: " + managerName + " | Status: " + status);
    }
}

Expected output

Manager: GameManager | Status: DontDestroyOnLoad

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 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); Correct answer
  • Object.PersistForever(gameObject);

Explanation: DontDestroyOnLoad() is the built-in Unity method protecting the target object from automatic cleanup on scene changes.

2 Safeguard object from scene cleanup

Question
____(gameObject);
Answer
DontDestroyOnLoad(gameObject);

Explanation: The DontDestroyOnLoad function is called to preserve an object across scene transitions.

3 Persistence concepts

Term Meaning
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

All lessons in Intermediate