Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Object Lifecycle on assembly recompile

Discussion in 'Editor & General Support' started by Guedez, Jan 23, 2020.

  1. Guedez

    Guedez

    Joined:
    Jun 1, 2012
    Posts:
    827
    Seeing https://docs.unity3d.com/Manual/ExecutionOrder.html I see that it's missing the information when the assemblies are unloaded/reloaded.This is making me not being able to release some compute buffers that are created on Awake.

    This is how I think it's happening:
    (0 buffers)On Enter Play mode(32 buffers) -> Awake gets called (32 buffers created)
    (32 buffers)On Exit Play Mode(32 buffers) -> OnDestroy(32 buffers released) is called and Awake(32 buffers created) is called right after
    (32 buffers)On Assembly reloaded(64 buffers) -> OnDestroy is not called and Awake is called right after reloading, therefore 32 buffers leaked
    Is this correct?
     
  2. Xilliah

    Xilliah

    Joined:
    Feb 24, 2021
    Posts:
    4
    Better late than never,

    Yea - OnDestroy() is unfortunately unreliable for releasing buffers and the like. As you mentioned it is not called on recompile and the Unity editor will throw warnings in your face about the buffers not having been released.

    Personally I like to use OnDisable() for this, as it is actually called and it's plain and simple. I call DeInit() from there.

    Right before rendering I typically run an Init() which creates the buffers if _isInit is false. This allows me to call DeInit() function from OnValidate(), which means any values changed in the inspector will be properly applied to the shader. Furthermore if the script or game object becomes disabled, and enabled again, it will still work properly.

    However, you can also choose to hook up to the assembly reload events in case you want to get fancy.