Quick question regarding event listeners and their removal

Hi

Throughout the course we make use of events and event subscribers / listeners and so forth, how does C# (/ unity) deal with removing these listeners? I come from the PHP / JS world and it’s best practice to remove any listeners.

I’m not knocking anything shown so far it’s all fantastic, just wondered if I should manually remove these listeners? Like in OnDestroy or some other destructor method?

Cheers

It kinda depends on the lifetime and logic. C# isn’t going to automatically unsubscribe from them. If the listener is going to live for the duration of the game, it kinda doesn’t matter if you don’t unsubscribe because they will die with the application, although I prefer to explicitly unsubscribe. A good rule is

  • If you subscribe in Awake(), unsubscribe in OnDestroy(), and
  • If you subscribe in OnEnable(), unsubscribe in OnDisabled()

If you subscribe anywhere else, you will have to consider the logic and unsubscribe appropriately. In the ‘Third Person Combat & Traversal’ course we use a state machine and often subscribe in the state’s Enter() method, but then unsubscribe again in the Exit() method.

1 Like

Yea I personally like to be quite explicit about things, I have been using OnDestroy and it’s all working fine so far.

Thanks for the insights :+1:

I personally prefer to subscribe in OnEnable() and unsubscribe in OnDisabled(), but sometimes I want an object to still listen, even if it is disabled. Then I’ll use Awake()/OnDestroy() respectively

1 Like

That makes sense, I am trying to gain a broad range of tools when it comes to unity, was reading up on object pooling and so subscribing on enable and unsubscribing on disable makes a good case for itself, thanks again.

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

Privacy & Terms