Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Question OnDestroy callback alternative

Discussion in 'Scripting' started by lweist3317, Apr 13, 2024.

  1. lweist3317

    lweist3317

    Joined:
    Oct 12, 2017
    Posts:
    34
    Ive written an [ExecuteAlways] Monobehavior which needs to unsubscribe from certain events when it is destroyed. The issue with that is that OnDestroy is never called if the Monobehavior was previously disabled.

    Is there any alternative to the OnDestroy callback that is guaranteed to be called no matter what?
     
  2. dstears

    dstears

    Joined:
    Sep 6, 2021
    Posts:
    156
    I typically unsubscribe/resubscribe to events in the OnDisable and OnEnable functions respectively. Would that work in your use case?
     
    CodeSmile and Kurt-Dekker like this.
  3. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    6,532
    In edit mode or playmode?

    In edit mode the component naturally isn't being destroyed otherwise ... whoops, it would be gone. ;)
    In playmode it should run OnDestroy at the latest when you exit playmode.
     
  4. lweist3317

    lweist3317

    Joined:
    Oct 12, 2017
    Posts:
    34
    Thats what I had been doing, but my MonoBehavior's got quite a few methods on it that should work whether or not the it is disabled.

    I've looked some more myself and it seems like there isnt any guaranteed destruction callback :( I guess I'll have to stick with OnEnable/Disable subscriptions and testing whether or not the component is enabled in all public methods.