Invoking and Unsubscribing From an Event

Hi there,

We used public events in the third person combat course and did a couple of things differently there. I’m just wondering whether these changes are important or not for the sake of my understanding.

The first is that when we’ve used actions in the past we would usually invoke it using code similar to this:

onConversationUpdated?.Invoke();

This carries out a null check to make sure there is a subscriber to the event and then triggers it if so. Sam just called it like a method in this video, does that perform the same job and bypass any null errors? It seems marginally easier to do it Sam’s way is all, so I’m wondering if there are any downsides?

The second is that when we’ve subscribed to an event in the past, it’s always been made clear that we need to unsubscribe from that same event so as to prevent memory leaks. Is there a reason that we wouldn’t unsubscribe from this event in OnDisable() or OnDestroy()?

Thanks in advance!

Josh

No, this will throw a NullReferenceException if there are no listeners. However, in the course the DialogueUI is part of the core object prefab, so there will always be a DialogUI - which means there will always be a listener.

Same as above; The DialogUI is always there. There is no need to unsubscribe because it needs to be always listening. It doesn’t get unsubscribed on destroy because it only ever gets destroyed when the game closes, and then everything gets destroyed so there’s no need to unsubscribe. We also need the DialogueUI to be listening when it is inactive - as you will see in the next lecture - because that is what will show the UI when a dialogue is triggered. So we also don’t unsubscribe on disable because it needs to continue to listen.

Hi Bixarrio,

Thanks for the quick response and the thorough explanation. That makes total sense.

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

Privacy & Terms