Subscribe event in start or onenable?

I often see subscribing to events in OnEnable and unsubscribe in OnDisable
so the event doesn’t try to call subscribers when some are null (for example if an enemy if dead and destroy from the scene)?

M. D.

I dont think it matters much, its up to you in the end i would say: how you design your code.

I mean; if you have a method which would for example kill your character or an enemy character
and destroy the gameobject, you could just as well unsubscribe in there before you do so.

I personally prefer OnEnable() and OnDisable() because it means the component will only handle the event if it is active. But in some cases you may want to have disabled components to also respond to events. So, then you can put them in Awake() and OnDestroy().

OnEnable() is called just after Awake() and OnDisable() is called just before OnDestroy(), so the events will be hooked and unhooked when objects are created and destroyed regardless of whether or not you used OnEnable()/OnDisable() or Awake()/OnDestroy(), but disabled components will still be listening to events if you subscribed in Awake()

NOTE Awake() above can be substituted with Start() but be aware that Start() is called after OnEnable()

1 Like

A little more on this:

If you are using OnEnable() then you should always have an unsubscribe in OnDisable() or you will start to stack events on GameObjects that might turn on and off (like UI).

If you are using Awake()/Start() to subscribe to components event on the same GameObject, you can skip unsubscribing if the only way the component would be destroyed is if the GameObject would be destroyed, but if the component event is on another GameObject, then you must unsubscribe in OnDestroy() or you could create a null reference error.

2 Likes

Thank you Bixarrio.

Thank you Brian, I should have figure it myself, if the event is on the same gameobject there is no chance it can call anything if it is destroyed.

M. D.

Privacy & Terms