Search Unity

OnApplicationQuit, OnDisable, OnDestroy

Discussion in 'Documentation' started by OriginialTin, Jun 23, 2015.

  1. OriginialTin

    OriginialTin

    Joined:
    Jun 13, 2013
    Posts:
    2
    Odd question, according to the docs here:

    http://docs.unity3d.com/Manual/ExecutionOrder.html

    It appears that these three methods should execute in the order:

    OnDisable
    OnDestroy
    OnApplicationQuit

    However they appear to actually execute in the order:

    OnApplicationQuit
    OnDisable
    OnDestroy

    Am I just reading the docs wrong or are they actually incorrect or out of date?
     
  2. LaneFox

    LaneFox

    Joined:
    Jun 29, 2011
    Posts:
    7,536
    If you've already used Application Quit, why does it matter if OnDisable or OnDestroy run?
     
  3. OriginialTin

    OriginialTin

    Joined:
    Jun 13, 2013
    Posts:
    2
    I have a singleton that is being re-created whilst the application is being quit or play mode is being exited. The singleton is being destroyed and then another object is trying to use one of the singletons methods in its OnDisable and thus re-creating the singleton which then persists in the editor after play mode has been exited.

    A bit of googling around suggested the solution was to put a quitting bool in that is set true in OnApplicationQuitting, it does solve the issue I am having, but I'm seeking a bit of clarification that the execution order is actually as it appears to be and not how it seems to be in the docs.
     
    elenzil likes this.
  4. liortal

    liortal

    Joined:
    Oct 17, 2012
    Posts:
    3,562
    We had a similar issue with a singleton. Since it was created lazily when accessing its Instance property, i add another property that lets you test if the singleton exists:
    Code (CSharp):
    1. public class MySingleton
    2. {
    3.     private static MySingleton instance;
    4.  
    5.     public static MySingleton Instance
    6.     {
    7.         get { ... }
    8.     }
    9.  
    10.     public static bool InstanceExists
    11.     {
    12.         get { return instance != null; }
    13.     }
    14. }
    This will not solve the issue you client code that attempt to access the singleton after it's destroyed though (unless you wrap all code that uses it with a check to see if it exists).
     
    Ghetaldus likes this.