- Home /
Is it possible to detect if an Object is *being* destroyed?
It is easy to check if a UnityEngine.Object has been destroyed by checking it for null. But, because Destroy is by default not immediate (and the documentation recommends against using immediate for some reason) there is a brief window until the next frame where an object is on death row but obj == null returns true.
Is it possible to check whether Destroy has been called on an object but it is not yet destroyed?
Answer by crohr · Jun 11, 2015 at 03:41 AM
The Unity method OnDestroy will get called when the object has had Destroy called on it.
void OnDestroy()
{
// Do whatever
}
It would not be possible to detect whether an inbuilt Object types are being destroyed with this method. I'm looking for a general purpose solution.
I you are try to check for when a specific Component is destroyed, then the answer is no, you can't deter$$anonymous$$e that a Component is in the process of being destroyed.
Could you tell us more about what specifically you are trying to accomplish, maybe there is another solution that could help you?
I am creating a general purpose Unity Object serializer. It's better not to serialize objects that are being destroyed.
Answer by maccabbe · Jun 11, 2015 at 04:05 AM
I'm not aware of anything built into unity that would work like
if(gameObject.isDestroyed)
However, it is possible to mark the gameObject as about to be destroyed yourself. For instance rename the gameObject or change the tag, i.e.
gameObject.name="ToDestroy";
GameObject.Destroy(gammeObject);
then you can check however you have decided to mark your gameobject
if(gameObject!=null&&gameObject.name!="ToDestroy){
I am looking for a general solution for all subclasses of UnityEngine.Object. This would not work for example in the case of components.
Your answer
Follow this Question
Related Questions
Passing information error 0 Answers
Getting all Object to go next scene. 1 Answer
if object is destroyed 2 Answers
How to destroy a unit contained in multiple lists 1 Answer
What is the reason for this NullReferenceException? 1 Answer