Hi, how can i find a second child of a gameobject by name?
this is the part of the code:
function Update (){
var ray : Ray = playerCamera.ViewportPointToRay (Vector3(0.5,0.5,0));
var hit : RaycastHit;
if (Physics.Raycast (ray, hit, distanceDetection)){
if(hit.transform.name == "Bone"){
target = true;
} else {
target = false;
}
} else {
target = false;
}
}
I need to find the child of a child gameobject named “Bone”, but i cant find it this way.
You can specify the path name to find a “grandchild”, like in the Transform.Find example:
aFinger = transform.Find("LeftShoulder/Arm/Hand/Finger");
But if you have more than one child with the same name, you can iterate through all children comparing the names or tags:
for (var child in transform){
if (child.name == "Bone"){
// the code here is called
// for each child named Bone
}
}
In your code, you could also use the child found to search in its own children:
if (hit.transform.name == "Bone"){
target = true;
var boneChild = hit.transform.Find("Bone");
if (boneChild){
// bone child found
}
} else {
...
IMD
June 12, 2013, 12:01pm
3
Here’s a little function I just cooked up that might come in handy…
static public GameObject getChildGameObject(GameObject fromGameObject, string withName) {
//Author: Isaac Dart, June-13.
Transform[] ts = fromGameObject.transform.GetComponentsInChildren();
foreach (Transform t in ts) if (t.gameObject.name == withName) return t.gameObject;
return null;
}
vladibo
November 16, 2018, 2:24am
5
internal static Transform FindChildByRecursion(this Transform aParent, string aName)
{
if (aParent == null) return null;
var result = aParent.Find(aName);
if (result != null)
return result;
foreach (Transform child in aParent)
{
result = child.FindChildByRecursion(aName);
if (result != null)
return result;
}
return null;
}
Know this is old – but still a useful question… here’s a solution based on some of the responses - but with a couple corrections / enhancements…
public GameObject GetChildGameObject(GameObject fromGameObject, string withName)
{
var allKids = fromGameObject.GetComponentsInChildren<Transform>();
var kid = allKids.FirstOrDefault(k => k.gameObject.name == withName);
if (kid == null) return null;
return kid.gameObject;
}
List childrens = new List();
int count = 0;
while (count < gameObject.transform.childCount)
{
childrens.Add(gameObject.transform.GetChild(count).gameObject);
count++;
}
UnityEngine.GameObject.Find(“name”) finds any gameobject by name. Just make your child have a unique name please! But remember: It’s computationally intensive.
Using Linq:
var allKids = GetComponentsInChildren<Transform>()
var kid = allKids.Where(k => k.gameObject.name == name).FirstOrDefault();