When to subscribe and unsubscribe

Would it be good practice to always have any classes unsubscribe from any events they have subscribed to in OnDisable/OnDestroy? Or should you only unsubscribe when you know it’s going to throw an error?

If the calling event is on a class that will be destroyed along with the subscriber, you can technically get away without unsubscribing to the event. This is, however, not best practice. Not unsubscribing from a static event or an event on an class that will remain even after the subscriber is destroyed will always lead to errors.

Ideally, you should always unsubscribe from events in OnDisable and OnDestroy as a matter of habit. By sticking with this detail even when it seems unneccessary, you avoid complications when it truly is necessary.

Privacy & Terms