- Home /
Prevent destruction of an object's child
I have a simple question that I just can't seem to find an answer to. I have a script that automatically cleans up an object by calling Destroy
on it. This works as intended, and proceeds to destroy the object along with its children.
However, my problem is that in a specific scenario the destroyed object may have some child object that I don't want to destroy. How would I prevent that? I figure I'd have to use OnDestroy
inside the child object, but nothing I can think to add actually stops the object from being destroyed.
Thanks in advance!
Edit: Clarified title to be specific to child objects.
Seems like you would want to unparent any child objects you want to keep, before destroying the parent object
like childGO.transform.parent = null;
So I'd need to include a special check inside the parent for this scenario? Is there no way to do it from the child? Thanks for the response.
Answer by baozi · Jul 26, 2013 at 09:56 PM
I managed to solve this by using BroadcastMessage("MySpecialCheck", SendMessageOptions.DontRequireReceiver)
right before the Destroy
call and including a handler ("MySpecialCheck") inside the child that removes itself from the hierarchy to avoid destruction. This way I could include a child-specific handler for each object that needed an exclusion case without muddying the parent's code.