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

When it is destroyed and the game continues

Discussion in 'Scripting' started by chengwang2077, Apr 8, 2021.

  1. chengwang2077

    chengwang2077

    Joined:
    Nov 23, 2019
    Posts:
    131
    ondestroy will be executed when the scene is switched and when the game ends. I only want to execute it when the scene continues. Is there any good way?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,520
    Usually you set a flag for when the game is running or not, then decide to act based on that flag.

    You can also consider using OnDisable() instead of OnDestroy()
     
    Joe-Censored likes this.
  3. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Code (csharp):
    1. public static bool GameOverDude = false;  //set to true when the game is over
    2.  
    3. void OnDestroy()
    4. {
    5.     if (GameOverDude)
    6.     {
    7.         //Do whatever you want this script to do when destroyed and game is over
    8.     }
    9.     else
    10.     {
    11.         //Do whatever you want this script to do when destroyed but game continues
    12.     }
    13. }
     
    Kurt-Dekker likes this.
  4. chengwang2077

    chengwang2077

    Joined:
    Nov 23, 2019
    Posts:
    131
    I try to modify OnGameDude in OnApplicationQuit()
    But sometimes OnApplicationQuit will be executed later than OnDestroy
    How to determine if the player has quit the game?
     
  5. chengwang2077

    chengwang2077

    Joined:
    Nov 23, 2019
    Posts:
    131
    It seems that OnApplicationQuit does not work when the object is inactive
     
  6. chengwang2077

    chengwang2077

    Joined:
    Nov 23, 2019
    Posts:
    131
    If the object belongs to DontDestroyOnLoad, then the switching scene has nothing to do with it, but if it happens to be destroyed when the scene is switched, according to the default practice, it will mistakenly think that it is the destruction caused by the scene switching
    The situation of destruction is very complicated. It would be great if the engine could provide more state.