In this lesson, you will learn how to trigger specific code automatically the moment a Game Object is removed from your scene using the OnDestroy lifecycle method.
Why Clean Up?
In Unity, when you call Destroy(gameObject) or load a new scene, the object is removed from memory. However, sometimes your script might be holding onto "loose ends"—like a reference to a global event manager or a temporary file—that doesn't know the object is gone. If you don't clean these up, you can cause memory leaks or errors where your code tries to communicate with an object that no longer exists.
Implementing OnDestroy
The OnDestroy method is a built-in message sent to your script by the Unity engine just before the object is destroyed. It is the perfect "final goodbye" for your components.
Here is a common scenario where you might need to unsubscribe from an event:
using UnityEngine;
public class EnemyCleanup : MonoBehaviour
{
private void Start()
{
// Imagine we subscribed to a global Game Event
GameEvents.OnGameOver += HandleGameOver;
}
private void OnDestroy()
{
// Crucial: Unsubscribe to prevent memory leaks!
// If we don't do this, the event might try to trigger
// a function on an object that has already been destroyed.
GameEvents.OnGameOver -= HandleGameOver;
Debug.Log("Object destroyed: Cleaning up references.");
}
private void HandleGameOver()
{
Debug.Log("Game Over received!");
}
}
When is it called?
OnDestroy runs when:
- You explicitly call
Destroy()on the object. - The scene ends or a new one is loaded (which destroys all objects in the current scene).
- The Play Mode is stopped in the Unity Editor.
By keeping your cleanup logic inside OnDestroy, you ensure your project remains stable and doesn't leave "ghost" references behind that could haunt your performance later on. Always check if your script has registered for external services or events, and if so, use OnDestroy to revoke those connections.
Key Takeaway: Use the OnDestroy method to clean up event subscriptions and nullify external references to ensure your game remains performant and bug-free when objects are removed.