- Home /
How to have child object remain after parent is destroyed?
hi,
I have an enemy that fires an object onto a wall that appears to morph into another shape when it lands. Currently, I have this wall shape as a prefab child of the enemy with its end position set and its renderer turned off. So when the initial projectile ball is fired (instantiated as normal) at the wall and appears to collide, the renderer of the wall object is turned on. I have done it this way to avoid further instantiation of objects.
Now, my question is that as this wall object is a child of the enemy, it will get destroyed along with it when the enemy is shot. So, I was wondering what the best way would be to set it up so that the wall object remains after the enemy is gone from the scene? Possible to detach the child before destroying the enemy?
Thanks
Answer by Khada · Sep 19, 2012 at 02:46 PM
Edited original answer based on feedback
Here is how to unparent a child object before you delete yourself.
Transform child = FindChild(gameObject, "ChildName"); //Replace "ChildName" with the child objects name.
child.parent = null;
gameObject.Destroy();
And here is the FindChild method:
public Transform FindChildTransform(GameObject parent, string name)
{
Transform child = null;
foreach(Transform trans in parent.transform)
{
if(trans.name == name)
{
child = trans;
if(child != null)
return child;
}
else
{
child = FindChildTransform(trans.gameObject, name);
if(child != null)
return child;
}
}
return child;
}
I think it is the other way around. He wants to keep the child alive and kill the parent. Your solution unparent the child and kills it. Or am I confused?
Ah yes, so EnemyObject should be the child, not the enemy here then?
Ah, yes. Sorry about that. I'll edit the answer to reflect this.
Your answer
Follow this Question
Related Questions
Destroyed child still is referenced. 1 Answer
Destroy(other.gameObject) isn't destroying parent, only children 2 Answers
uitoolkit slide out menu? (made for mobile but taking all ideas, except for OnGUI calls) 1 Answer
find ALL children of a parent 1 Answer
Does a child transform take the name of its parent in unity 3D? 1 Answer