Understanding Component Destruction in Unity

We did a post about what happens when an object is created and initialized. we also did one on different update methods. Now it’s time to see what happens at the end of the object life-cycle with OnDisable() and OnDestroy().

This time, we don’t have so many methods to cover as there are only two of them, but the question remains the same. When they are called, and what should you use them for? ?‍♂️

If you remember post about object initialization, it was mentioned that there is OnEnable() method. Of course, by its name, you can guess when it’s called. Opposite to that is OnDisable() method, which is called when component becomes disabled or game object becomes inactive. Both things can happen multiple time during a game, so these two methods would also be called as many times as is necessary.

The OnDestroy() method on the other hand will be more like a destructor of the object or the component. It serves exactly opposite purpose to Awake() method, and you should deinitialize variables and references in it.

When to use each of them?

In OnDisable() method, as name suggests, you should disable any operating logic in that object. These could be stopping animations, disabling AI, or detaching events.

OnDestroy() is a place where you should put deinitialization of the variables or references. I know that we in C# there is GarbageCollector[link], but it’s good practice to clean up space after you’re done with your work. ?

Exercise for you

Create a script which has all methods mention in this post as well as in the post about initialization and updates. After you do this, start playing with activating and deactivating game object and component.

Let me know what you found out in the comment section below! ?

And if you want to get notified on future content, sign up for the newsletter!

And I hope to see you next time! ?

3 4 votes
Article Rating
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x