- Home /
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?
Answer by Eric5h5 · Apr 30, 2010 at 08:23 PM
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");
}
}
Note, that OnDisable will be called (with the gameObject set to inactive) when loading a new level, even if DontDestroyOnLoad has been called.
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...
The way to get an OnDestroy callback is for UT to program one into Unity.
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.
Your answer
Follow this Question
Related Questions
Track OnDestroy() Who called it? 1 Answer
How to start animation after object is destroyed ? 1 Answer
Perform a Task when Objects are Destroyed 4 Answers
OnDestroy() called when ending application. Any alternatives? 1 Answer
I want to use the current scale x of my object to help calculate my score. . . 1 Answer