Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

Bug IS THIS A BUG? Unity calls OnDestroy on Game Objects when entering or leaving maximized window

Discussion in 'Scripting' started by superjustin5000, Sep 8, 2023.

  1. superjustin5000

    superjustin5000

    Joined:
    Apr 12, 2015
    Posts:
    16
    I have a MonoBehaviour Script with OnDestroy implemented, with a simple Debug log
    When running the game from the editor, whenever I switch from a normal Game window to the maximized, or from maximized to normal, the debug log is printed in the console, and any other code in OnDestroy is also executed, however, the game object was never destroyed.
    Is this a bug, or known, I have not found documentation on it.
    It's making debugging pretty frustrating as OnDestroy is meant for when things are actually being destroyed, so code is executing when it shouldn't be.

    Thanks,
     
  2. Lurking-Ninja

    Lurking-Ninja

    Joined:
    Jan 20, 2015
    Posts:
    10,088
    Unity 2022.3.9f1 (LTS) doesn't do this for me.
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    37,265
    That seems odd, but I wouldn't be surprised honestly.

    Historically OnDestroy() has been a troubled function, often requiring silly shims like
    public static bool applicationIsExiting;
    and annoyingly hairy code interlocks to prevent fiddling with things that might new up GameObjects such as singletons and whatnot.

    Instead, try and move stuff out of Awake / OnDestroy and instead put it in OnEnable / OnDisable.

    The OnEnable / OnDisable lifecycle pair is FAR more robust and reliable.
     
  4. superjustin5000

    superjustin5000

    Joined:
    Apr 12, 2015
    Posts:
    16
    Got it, I'm on 2021.3.13 and I've noticed this happening for a long time, maybe it's finally fixed.
     
  5. superjustin5000

    superjustin5000

    Joined:
    Apr 12, 2015
    Posts:
    16
    That's fair, I'll check if OnDisable has similar bazar behavior.