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?
1 Answer
1Edit: 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");
}
}
Thanks for the quick reply!
– anon33223845Note, that OnDisable will be called (with the gameObject set to inactive) when loading a new level, even if DontDestroyOnLoad has been called.
– Matthew_AThe way to get an OnDestroy callback is for UT to program one into Unity.
– Eric5h5I 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.
– Wolfram@Wolfram: The OnDisable behavior changed between Unity 2.6 and Unity 3.0. I suppose they might have changed it back in 3.3, but it's irrelevant, since OnDestroy was added in Unity 3.2, so you don't have to bother trying to use OnDisable for that purpose anymore.
– Eric5h5