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

How to do some action when I leave game mode

Discussion in 'Scripting' started by arsnyan2002, Jan 5, 2021.

  1. arsnyan2002

    arsnyan2002

    Joined:
    Apr 30, 2019
    Posts:
    30
    I was trying to destroy all children objects from my gameobject, but got to a problem of "how do I do something when I leave game mode and enter edit mode".
    I think I can use OnValidate somehow, but maybe there already is an event function that I need. Is there?

    I also was thinking about changing the way I spawn objects and that I should change it to Object.Instantiate (now I just use new GameObject()), but I don't need to clone objects, I need to create them from scratch.
    And no, all of those objects do not get destroyed automatically when I leave game mode.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,519
    Well this is the first problem to solve. Any GameObjects created during the normal part of the scene run will be gone when the game is stopped and returned to editor mode.

    If you create stuff in OnDestroy or OnDisable or other such "edge of lifecycle" places, you have to be extremely aware of the timing of these function callbacks or else you will have random stuff added to your scene when you stop.

    To further understand lifecycle, here is some timing diagram help:

    https://docs.unity3d.com/Manual/ExecutionOrder.html
     
    arsnyan2002 likes this.
  3. arsnyan2002

    arsnyan2002

    Joined:
    Apr 30, 2019
    Posts:
    30
    What's weird about that is that the problem got solved itself. It just happend once all of a sudden. And now it performs as it should. I didn't change any line of code, just tested it by entering play mode and then leaving it. Why >:|