In this lesson, you will learn how to use OnEnable and OnDisable to manage resources and event listeners exactly when a component is toggled on or off.
Understanding Component Lifecycle
So far, you’ve used Awake and Start to set up objects when a scene begins. However, game objects and components are often turned on and off mid-game—for example, a menu screen appearing or a trap activating when a player enters a room.
When you check or uncheck the box next to a component in the Inspector, Unity triggers two specific lifecycle methods: OnEnable and OnDisable. These are your "hooks" for ensuring your script stays synchronized with the game state.
Using OnEnable and OnDisable
Think of OnEnable as a "subscription" phase. If your script needs to listen to an input event or start a background process (like a timer), you should initiate those in OnEnable.
Conversely, OnDisable is your "cleanup" phase. If you forget to unsubscribe from events or stop active processes when a component is deactivated, you can cause memory leaks or errors where your script tries to update objects that no longer exist.
Here is how a typical implementation looks:
using UnityEngine;
public class ResourceHandler : MonoBehaviour
{
private void OnEnable()
{
// Subscribe to events or allocate resources
Debug.Log("Component is active: Resources allocated.");
}
private void OnDisable()
{
// Unsubscribe from events or stop timers to prevent errors
Debug.Log("Component is inactive: Resources cleaned up.");
}
}
By using these methods, you ensure that your code only runs when the component is actually working. For example, if you have a script that listens for input, you should subscribe to the input event in OnEnable and unsubscribe in OnDisable. This ensures that your script doesn't try to process movement or clicks while the object is disabled, keeping your game running smoothly and predictably.
Key Takeaway: Use OnEnable for registering events and allocating resources, and always use OnDisable to unsubscribe and clean up, ensuring your components behave predictably when toggled.