In this lesson, you will learn how to implement the DontDestroyOnLoad pattern to ensure your manager classes persist seamlessly across scene transitions without creating duplicate instances.
The Singleton Persistence Challenge
When you move between scenes in Unity, the engine destroys all objects in the current scene to make room for the next. While this is great for level-specific geometry, it is disastrous for managers—like your AudioManager or GameSessionManager—that need to track data throughout the entire lifecycle of the game.
If you simply place a Singleton in your first scene, loading a second scene will destroy it, and if you have a copy in that second scene, you might end up with two instances fighting for control.
Implementing Persistent Logic
To solve this, we use DontDestroyOnLoad. When a script executes, it checks if a global instance already exists. If it doesn't, it assigns itself as the instance and marks itself to persist. If an instance already exists, the new object realizes it is a duplicate and deletes itself immediately.
public class GameManager : MonoBehaviour
{
public static GameManager Instance { get; private set; }
private void Awake()
{
if (Instance != null && Instance != this)
{
// We found a duplicate, destroy this new object
Destroy(gameObject);
return;
}
Instance = this;
// Make this object persist through scene loads
DontDestroyOnLoad(gameObject);
}
}
Why this matters
By placing this logic in Awake, you ensure the Singleton initializes before any other components try to access it. DontDestroyOnLoad moves the object to a special "DontDestroyOnLoad" scene managed by Unity, which exists outside your standard scene hierarchy. This guarantees your GameManager remains alive while the rest of your scene is cleared away. This approach is highly effective for systems that need to maintain state, such as player inventory, current score, or active network connections, providing a stable foundation for the rest of your game's architecture.
Key Takeaway: Use the DontDestroyOnLoad pattern combined with a self-destruct check in Awake to prevent duplicate instances and guarantee your Managers remain persistent across scene transitions.