Search Unity

Will loading a new scene automatically destroy/unsubscribe event handlers?

Discussion in 'Scripting' started by blablaalb, Aug 27, 2019.

  1. blablaalb

    blablaalb

    Joined:
    Oct 28, 2015
    Posts:
    53
    I have subscribed to an event using lambda expression therefore I can't unsubscribe it. Now I'm wondering if the subscription will be preserved when the scene is reloaded. The component is not non-destroyable which means in theory it should be destroyed therefore the subscription? If the subscription will be preserved then I better write a new method and unsubscribe it manually.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    The event will NOT be unsubscribed automagically. This means anything linked will not be eligible for garbage collection, even though the scene is long gone and the objects are unusable. It's usually not a huge problem, but it can certainly cause memory leakage, as everything referenced is ineligible for cleanup.

    The usual pattern with Unity3D MonoBehaviors is to subscribe in the OnEnable() method and to unsubscribe in the OnDisable() method. For a lambda you can cache its reference locally and then unsubscribe in OnDisable().

    Another approach is to have your broadcaster listen for the SceneManager's .sceneUnloaded delegate and just use that as a point to set your delegates to null, which will remove all references to previously-subscribed objects/methods. Brutal but effective.
     
    krzpia, m-y and blablaalb like this.
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    Just to clarify, if both the subscriber and the delegate get destroyed by a scene load, there should be no retained references. You don't have to unwind all that yourself in that case. I was assuming you were subscribing your lambda to a non-destroyable GameManager-style long-lived object.
     
    ben-rasooli likes this.