b20 event hook problem

This is a bit odd, and I think its a bug.

I have an event manager and I hood to it like this:

    void OnEnable()
    {
        Freekstorm_EventManager.OnSetEditMode += OnSelectEditMode;
    }

    void OnDestroy()
    {
        Freekstorm_EventManager.OnSetEditMode -= OnSelectEditMode;
    }

  void OnSelectEditMode(bool isEditing)
  {
  }

At start I connect an object, the OnEnable occur and the events start flowing. At some point I destroy the object. OnDestroy is called and I unhook. But then some time later (seconds), the hook is called again from the event manager even though I’m unhooked and destroyed, thus this==null and it bombs.

Can anyone explain if this is a bug or I’m doing something wrong.

Are you sure that the OnEnable event is firing only once for the object in question?

Shaderop Your right! But the reason is not obvious.
The OnDestroy isn’t called when I destroy the object, but at the end of the frame. By which time other events have occurred that called into the object, including setting the object to enabled, which causes the second hook.

So for all the objects that I hook, I’m going to have to remember that I hooked them, so it cant happen again.

I would have thought that a better sequence would be
OnDisable
OnDestroy
wait for end of frame
Garbage it

rather than
OnDisable
wait for end of frame
OnDestroy
Garbage it

Anyway thanks for you help.

Hi freestorm,

just browsing, feeling happy and thus wanted to give you a heads-up when using events in OnEnabled. Without any knowledge on how you are using that piece of code, there is a possibility of registering multiple listeners, as OnEnable() can be called multiple times.

I have found that coupling event registering and unregistering in the following way works the best for me:
Register → OnEnable()
Unregister → OnDisable()

and if you need to unregister the listeners in OnDestroy():
Register → Awake() or Start() (whichever suits your needs)
Unregister → OnDestroy()

Hope this helped in any way :slight_smile: