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

OnDisable() - Destroy or Disable?

Discussion in 'Scripting' started by MatthewW, Dec 24, 2007.

  1. MatthewW

    MatthewW

    Joined:
    Nov 30, 2006
    Posts:
    1,356
    Is there any way to differentiate between an object being destroyed or simply disabled in OnDisable()?
     
  2. bronxbomber92

    bronxbomber92

    Joined:
    Nov 11, 2006
    Posts:
    888
    Code (csharp):
    1. OnDisable()
    2. {
    3.      if( !gameObject.active ) // or maybe use if( !enabled ) if you just want to check this script
    4.      {
    5.           // it was disabled
    6.      }
    7. }
    I don't know if this works, but I think it should :)
     
  3. MatthewW

    MatthewW

    Joined:
    Nov 30, 2006
    Posts:
    1,356
    Ah ha! Clever, that looks like it works.

    Can you think of any magical way to check if OnEnable() is being called from a disabled object (rather than at object creation)? I track with an "initialized" boolean I set at the end of Start(), but it feels cumbersome.
     
  4. bronxbomber92

    bronxbomber92

    Joined:
    Nov 11, 2006
    Posts:
    888
    You could create a list of all GameObjects in the scene in a Manager class (or where ever), and if the gameobject is all ready contained in the list/array, then it all ready existed, if it didn't then it's a new gameobject (make sure to you add itself to the list.

    Alternatively you could do something like this:
    Code (csharp):
    1. private var OnEnabledCalled : boolean;
    2.  
    3. function Awake()
    4. {
    5.     OnEnabledCalled = false;
    6. }
    7.  
    8. function OnEnabled()
    9. {
    10.     if( !OnEnabledCalled )
    11.     {
    12.         // the script was just created
    13.         OnEnabledCalled = true;
    14.     }
    15.     else
    16.     {
    17.         // the script all ready existed
    18.     }
    19. }
     
  5. bronxbomber92

    bronxbomber92

    Joined:
    Nov 11, 2006
    Posts:
    888
    Hi,

    I was just wondering, did these work for you?
     
  6. MatthewW

    MatthewW

    Joined:
    Nov 30, 2006
    Posts:
    1,356
    Checking for enabled in OnDisable() works really well.

    We do something similar to your code for OnEnable()--we have an "intialized" variable that starts false and becomes true after Start() is complete.