- Home /
Destroy parent of child gameobject?
So i know destroy(gameobject) will destroy the gameobject.
But my collider is a child of the main controller gameobject...and i want to destroy that part (so child + parent) gameobjects.
So how can i destroy the parent to a gameobject?
Answer by yeoldesnake 1 · Jun 27, 2012 at 09:20 AM
You can get the parent of a transform by using
transform.parent
Therefore you need to call
Destroy(transform.parent.gameObject);
Finally, if you only need the parent and not the child component destroyed:
var foo:GameObject;
foo=transform.parent.gameObject;
transform.parent=null;
Destroy(foo);
Thank you so much for this, I've been stuck on trying to make the player score every time he kills a prefab enemy, I feel like I've finally made progress on that now! :)
Answer by Creative-House-org · Dec 27, 2015 at 09:23 AM
Why not just use transform.DetachChildren()?
Answer by joshbowden42 · Sep 07, 2020 at 11:24 AM
how would you do this with an array?
It's enough to destroy the father one time. The others will be deleted automatically. Let's assume the array of game objects is object array.
void RemoveParent(GameObject[] objectList)
{
if(objectList.Length > 0)
Destroy(objectList[0].transform.parent.gameObject);
}
If you want the other objects from the father you must firstly detach them from a parent like here link text