Search Unity

  1. Looking for a job or to hire someone for a project? Check out the re-opened job forums.
    Dismiss Notice
  2. Unity 2020 LTS & Unity 2021.1 have been released.
    Dismiss Notice
  3. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    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:
    112
    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:
    13,753
    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:
    10,809
    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:
    112
    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:
    112
    It seems that OnApplicationQuit does not work when the object is inactive
     
  6. chengwang2077

    chengwang2077

    Joined:
    Nov 23, 2019
    Posts:
    112
    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.
     
unityunity