Search Unity

When to unsubscribe from Event?

Discussion in 'Scripting' started by Unlimited_Energy, Aug 24, 2019.

  1. Unlimited_Energy

    Unlimited_Energy

    Joined:
    Jul 10, 2014
    Posts:
    469
    Hi,

    I am trying to understand when to Unsubscribe/unregister from an event? it seems you can controll when the observer receives notifications by subscribing in the OnEnabled/OnDisabled. Would I unregister whenever the object is destroyed/disabled, and is there any other time I would need to unregister from teh event besides object destroyed or disabled/notActive?
     
  2. ADNCG

    ADNCG

    Joined:
    Jun 9, 2014
    Posts:
    994
    OnDisable works fine. It fires when both destroyed and disabled.
    Only if you don't want to know about the event anymore.
     
    Unlimited_Energy likes this.
  3. YetAnotherKen

    YetAnotherKen

    Joined:
    Jun 17, 2019
    Posts:
    30
    Another potential pitfall is when a method subscribes to an event. If you do not unsubscribe first, then you could end up with multiple callbacks when that event is triggered. That can get messy.
     
  4. Unlimited_Energy

    Unlimited_Energy

    Joined:
    Jul 10, 2014
    Posts:
    469
    not entirely sure what you mean sorry. I thought methods always subscribed to an event? do you have an example if you have time? Im having an aha moment with coding and a lot of crap is being tied together right now including this lol.
     
  5. ADNCG

    ADNCG

    Joined:
    Jun 9, 2014
    Posts:
    994
    Here, test it you'll understand it easily.

    Put this in scene
    Code (CSharp):
    1. using System;
    2. using UnityEngine;
    3.  
    4. public class Foob : MonoBehaviour
    5. {
    6.     public static EventHandler StuffDone;
    7.  
    8.     private void Update()
    9.     {
    10.         if (Input.GetKeyDown(KeyCode.Space))
    11.         {
    12.             StuffDone?.Invoke(this, EventArgs.Empty);
    13.         }
    14.     }
    15. }
    Then put this on another object
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class Bar : MonoBehaviour
    4. {
    5.     private void OnEnable()
    6.     {
    7.         Foob.StuffDone += OnStuffDone;
    8.     }
    9.  
    10.     private void OnStuffDone(object sender, System.EventArgs e)
    11.     {
    12.         Debug.Log("Fubar");
    13.     }
    14. }
    Press space. OnStuffDone is called once on "Bar".

    Disable bar and re-enable it, then press space again. It'll be called twice this time, and so on.

    That being said, you're safe with subbing in OnEnable and unsubbing on OnDisable. Personally I never ran into an issue or heard of anybody having one with this.
     
  6. YetAnotherKen

    YetAnotherKen

    Joined:
    Jun 17, 2019
    Posts:
    30
    I mean methods that can be used multiple times.
     
    Unlimited_Energy likes this.