x


OnDestroy notification?

I'd like to be notified when object is about to be destroyed. I don't see a GameObject.OnDestroy method, any way to know this?

more ▼

asked Apr 30 '10 at 08:15 PM

jc_lvngstn 1 gravatar image

jc_lvngstn 1
266 8 9 20

(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

Edit: OnDestroy now exists in Unity 3.2. No need for hacks anymore!

Use OnDisable. You can determine whether the script is being disabled or the object is destroyed/deactivated like this:

function OnDisable() { 
   if (gameObject.active) { 
      print ("Disabled");
   } 
   else { 
      print ("Destroyed or set inactive");
   } 
}

NOTE! The above code longer works the same in Unity 3. It works like this instead, which seems less useful:

function OnDisable() { 
   if (gameObject.active) { 
      print ("Disabled or Destroyed");
   } 
   else { 
      print ("Set inactive");
   } 
}
more ▼

answered Apr 30 '10 at 08:23 PM

Eric5h5 gravatar image

Eric5h5
80.3k 42 132 521

Thanks for the quick reply!

Apr 30 '10 at 08:27 PM jc_lvngstn 1

Note, that OnDisable will be called (with the gameObject set to inactive) when loading a new level, even if DontDestroyOnLoad has been called.

Oct 30 '10 at 12:55 PM Matthew A

Is there any way to have a OnDestroy callback?? this would be really usefull when child objects get destroyed and some cleanup needs to be done...

Jan 11 '11 at 02:12 PM David St-Hilaire

The way to get an OnDestroy callback is for UT to program one into Unity.

Jan 11 '11 at 10:04 PM Eric5h5

I just tried your code examples with Unity 3.3, and it behaves as described in your first code fragment, the second code fragment is not correct for 3.3.

Jun 15 '11 at 03:53 PM Wolfram
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x764
x166
x18

asked: Apr 30 '10 at 08:15 PM

Seen: 4741 times

Last Updated: Apr 04 '12 at 09:52 PM