Registering event listeners

Just a tip for anyone else that might have missed this.

I started using delegates/events some time ago and picked up that when you add an event listener, you should also keep things clean and remove it when the listening object is destroyed. It was suggested at the time that using OnEnable and OnDisable were good places to do this, eg.

private void OnEnable()
{
    UnitActionSystem.Instance.OnBusyChanged +=
              UnitActionSystem_OnBusyChanged;
}

private void OnDisable()
{
    UnitActionSystem.Instance.OnBusyChanged -=
              UnitActionSystem_OnBusyChanged;
}

The problem in this case is that the ActionBusyUI adds the listener at runtime, but after the first call to gameObject.SetActive(false), it is removed, because that triggers OnDisable().

In this case, I moved the de-registration call into the Destroy() method.

3 Likes

I, myself, am a fan of using OnEnable() and OnDisable() for event registration, but there is a post somewhere here that addresses this same thing and the conclusion (I think) was that you should use OnDisable() to unregister when you register in OnEnable() and use OnDestroy() to unregister when you register in Awake()

6 Likes

Yes, I saw that about 15 minutes after I posted my comment :slight_smile: It’s on the “Turn System” video.

3 Likes

Yeah when you have logic setting the game object disabled be careful with that.
Since I tend to use that what I normally do when I want to handle unsubscribe is do it on OnDestroy() and subscribe on Start()
However the reason why I don’t usually bother with unsubscribing is because when the scene changes all objects are destroyed and as long as the publisher and subscriber both get destroyed at the same time then everything works without issues, only a problem when one is destroyed before the other one.

4 Likes

Privacy & Terms