Should we be using OnEnable and OnDisable to sub and unsub from our events?

I just wanted to ask, would it make sense in this project to subscribe to and from events using the OnEnable and OnDisable methods? I’m thinking of our OnSelectedUnitChanged, OnSelectedActionChanged, and OnBusyChanged events. I remember watching a tutorial (not from gamedev.tv mind you though) in which the instructor put alot of emphasis on the importance of subbing and unsubbing to events using the OnEnable and OnDisable methods. I just wanted to ask if that would make sense to do for this project and if that is a best practice. Or, that would not make sense for this project and course? Thanks!

This is the video I mentioned by Unity: C# Events in Unity! - Intermediate Scripting Tutorial - YouTube

Around the 4-minute mark the speaker mentions the importance of setting up an unsubscribe when you subscribe.

You can, but in most of our cases the subscribers stick around for the full duration of the game. The game objects only ‘disable’ when the game stops and then it’s not going to make much difference because they don’t stay subscribed if the game is not running.
It is good practice, though, and may even cause bugs if you don’t unsubscribe in certain cases.
OnEnable and OnDisable is also not the only place you’d want this. You may want a subscriber to still listen for events, even when it is disabled - perhaps to have it enable itself again. In those cases you could subscribe in Awake or Start (or OnEnable - all depends on the use case), but you’ll unsubscribe in OnDestroy instead. You could also unsubscribe whenever you really want. Perhaps you only want to listen for an event once. The you can unsubscribe in the event handler itself.
But, yes. For short lived objects (ones that do not live for the duration of the game) you certainly want to unsubscribe events that you subscribed to

2 Likes

Thank you, that makes a lot of sense. And I hadn’t thought about objects that may listen when they are disabled. Even in our game, The Action Busy UI we created listens for an event that signals that the current unit is busy and if not, disables itself. So unsubscribing OnDisable would break our code. Thanks for the tips!

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms