In this lesson, you will learn how to manually clean up static manager references to ensure your game releases memory correctly during scene transitions and application shutdowns.
The Hidden Trap of Static References
In Unity, a static variable belongs to the class type itself, not to a specific object instance. When you assign a static reference to a MonoBehaviour (like a UIManager or AudioManager), that static variable holds onto the object in memory even if the scene containing that object is unloaded. Because the static reference acts as a "root" for the Garbage Collector, Unity cannot destroy the object, leading to memory leaks and potential "MissingReferenceException" errors when your code tries to access an object from an old, destroyed scene.
Implementing Cleanup Routines
To prevent this, you must explicitly nullify your static references when the object is destroyed. Since your managers are likely singletons or centralized services, utilize the OnDestroy method to clear these pointers.
Consider this implementation pattern:
public class AudioManager : MonoBehaviour
{
public static AudioManager Instance { get; private set; }
private void Awake()
{
if (Instance == null) Instance = this;
else Destroy(gameObject);
}
private void OnDestroy()
{
// Prevent the static reference from dangling after scene unloading
if (Instance == this)
{
Instance = null;
}
}
}
Why This Matters
When a scene unloads, Unity destroys the GameObject, but the static variable remains pointing to the memory address of the now-dead object. By setting Instance = null in OnDestroy, you signal to the Garbage Collector that the reference is no longer needed. This is especially vital when using DontDestroyOnLoad; you want to ensure that if the game restarts or the manager is re-instantiated, the static bridge is clean and ready for a fresh initialization.
Without this step, your game accumulates "ghost references," where your architecture thinks a system is active when the underlying memory is actually fragmented or orphaned. Always treat your static references as lifecycle-bound assets that require an explicit "off switch."
Key Takeaway: Always set your static manager references to null within the OnDestroy method to ensure the Garbage Collector can reclaim memory and prevent dangling pointers during scene transitions.