- Home /
How do I find a child object in a hierarchy of children?
I'm trying to (by the most efficient means possible) deparent a weapon object from an enemy on their death. The weapon object is parented to the hand bone, which is obviously down a long list of bone child heirarchies. I tried transform.Find but I couldn't get results, I'm assuming this is because it will only find immediate child objects, and not go down the whole hierarchy? I also tried BroadcastMessage but it crashed Unity in runtime (so obviously I used that very wrong).
So what is the best way to do this in C#?
Answer by Cherno · Sep 09, 2014 at 03:59 AM
You can just use GetComponentsInChildren, what you search for is up to you, you could just list all transforms and check if one has a certain tag or layer, or you could list all scripts or other components in the hierarchy.
Transform[] children = GetComponentsInChildren<Transform>();
foreach(Transform child in children) {
if(child.CompareTag("Weapon")) {
...
}
}
WeaponScript[] weapons = GetComponentsInChildren<WeaponScript>();
foreach(WeaponScript weapon in weapons) {
if(weapon.gameObject.name == "M16") {
...
}
}
}