Search Unity

  1. Unity Asset Manager is now available in public beta. Try it out now and join the conversation here in the forums.
    Dismiss Notice

b20 event hook problem

Discussion in '5.4 Beta' started by freekstorm, Jun 7, 2016.

  1. freekstorm

    freekstorm

    Joined:
    Nov 11, 2010
    Posts:
    86
    This is a bit odd, and I think its a bug.

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

    Code (csharp):
    1.  
    2.     void OnEnable()
    3.     {
    4.         Freekstorm_EventManager.OnSetEditMode += OnSelectEditMode;
    5.     }
    6.  
    7.     void OnDestroy()
    8.     {
    9.         Freekstorm_EventManager.OnSetEditMode -= OnSelectEditMode;
    10.     }
    11.  
    12.   void OnSelectEditMode(bool isEditing)
    13.   {
    14.   }
    15.  
    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.
     
  2. shaderop

    shaderop

    Joined:
    Nov 24, 2010
    Posts:
    942
    Are you sure that the OnEnable event is firing only once for the object in question?
     
  3. freekstorm

    freekstorm

    Joined:
    Nov 11, 2010
    Posts:
    86
    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.
     
  4. Psy_Duck

    Psy_Duck

    Joined:
    Jun 12, 2013
    Posts:
    9
    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 :)