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

Bug When I quit PLAY MODE, OnDisable monobehavior activate

Discussion in 'Editor & General Support' started by hyperkvlt, Nov 11, 2022.

  1. hyperkvlt

    hyperkvlt

    Joined:
    Aug 16, 2020
    Posts:
    37
    I don't know why OnDisable function from monobehavior would active whenever I quit playmode. I believe this is not supposed to happen since I didnt experience this before.

    Isn't OnDisable only active when the gameobject disabled or destroyed? Not when you quit playmode, right?

    I am using Unity Editor 2021.3.11f1

    EDIT:
    It seems to happen on 2021.3.13f1 too. Is there a way to stop OnDisable to activate when quitting Playmode?
     
    Last edited: Nov 11, 2022
  2. hyperkvlt

    hyperkvlt

    Joined:
    Aug 16, 2020
    Posts:
    37
    Okay, it's not a bug. This happened on 2019 version too.

    So, is there a way to, like, stop it? This ended up getting me errors because of some of my script do things on disable. I really don't want them to do anything when I quit playmode or quitting the game.
     
  3. hyperkvlt

    hyperkvlt

    Joined:
    Aug 16, 2020
    Posts:
    37
  4. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,610
    It's completely normal and has always been the expected behaviour. When you enter play mode, your current open scenes are backed up and copies of them are loaded. When you're done, any active scenes are unloaded.

    Unloading scenes includes Destroy()-ing every game object present in it. This means OnDisable and OnDestroy will be called for any that implement them when exiting play mode.

    I'm wondering what you're doing that's causing issues when exiting play mode. All these objects are getting destroyed so what are they manipulating that's causing issues?
     
    Linkruste likes this.
  5. hyperkvlt

    hyperkvlt

    Joined:
    Aug 16, 2020
    Posts:
    37
    Well, I didn't know that OnDisable and OnDestroy will be called upon quitting playmode (or quitting the game). They never mention this at all on the documentation. I just found out about this not too long ago after long google search.

    Since some of my scripts call other script using OnDisable, they naturally get NULL Reference if the called script get destroyed (because of quitting playmode) first.

    Well, I already found a way to circumvent this from other post after trial and error.
     
  6. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,610
    This is going to happen regardless how the scene is being unloaded. The order in which objects are disabled/destroyed isn't defined so having them act on other objects is a bad idea in general.