- Home /
Destroy Child of Game Object
I checked the first 10 pages from typing "Unity Destroy child" and all didn't have the advice I was looking for.
Currently I have:
function OnTriggerExit ( other : Collider )
{
outTile = other.gameObject;
Destroy (outTile.gameObject);
}
But the outTile game object has a child and I want to destroy THAT instead, not other.gameObject but other.gameObject.child (which doesn't work).
Although the other.gameObject.name can vary greatly, the child always has the same name as its parent + (clone).
Thx!
Answer by poday · Feb 02, 2013 at 08:47 AM
GameObject's can't directly access their children but every GameObject contains a Transform which can then access it's children. Something like:
for (var child : Transform in outTile.transform) {
if(child.name == outTile.name + "(clone)")
{
Destroy(child.gameObject);
}
}
You can reference http://docs.unity3d.com/Documentation/ScriptReference/Transform.html as Unity's documentation on Transforms.
Yeah this is what I was looking for! Thanks! http://docs.unity3d.com/Documentation/ScriptReference/Transform.html
Answer by DeveshPandey · Feb 02, 2013 at 08:25 AM
Try this-
function OnTriggerExit ( other : Collider )
{
outTile = other.gameObject;
Destroy (outTile.Find("ChildName"));
}
This worked, however, if there were other GameObjects with children with the same name, it didn't work. So I made the children's names unique and it was fine. Thanks!
Find() will do a global search in your scene, so it may cause lagging/freezing if you have a complex scene on a slow device.
@poday's approach is the way to go, assu$$anonymous$$g the child in question is a direct child of the object, and not a grandchild or deeper.
You're right. His method worked perfectly, although I needed to change "(clone)" to "(Clone)".