- Home /
GetComponentsInChildren problem
Good day, commUnity! I have a prefab of a character like this:
Say, I have an object iCharacter, instantiated from peasant prefab. I need to get the TargetLookAt child object from code. I tried the following ways:
1)
Transform targetLookAt = iCharacter.transform.FindChild("TargetLookAt");
if (targetLookAt != null)
_targetLookAt = targetLookAt.transform;
FindChild always returns null. It seems like it searches only among the first generation of children - if it is so, then ok, this code is incorrect.
2)
Transform [] children = iCharacter.GetComponentsInChildren <Transform> ();
foreach (Transform child in children)
{
if (child.name == "TargetLookAt")
{
_targetLookAt = child;
break;
}
}
This code seems to be correct. Moreover, GetComponentsInChildren should search for components in the whole hierarchy of a parent. So I expected to get all the transforms, parented to peasant. But instead I got only one Transform in the children array.
3) Ok, Transform is IEnumerable, so I can simply take the iCharacter.transform and look through all the child transforms in a loop:
for (int i = 0; i < iCharacter.transform.childCount; ++i)
{
var child = iCharacter.transform.GetChild (i);
if (child.name == "TargetLookAt")
{
_targetLookAt = child;
break;
}
}
Still no result, cause iCharacter.transform.childCount = 0 somehow. So there are two questions: - How to find a specific child in a GameObject, instantiated from a prefab? - Why all my code samples don't work?
P.S. I have a sense, that all these problems have one common solution.
I have the same problem. I have two game scenes and this works on one and does not work on the other. I can't see whats the difference between them.
Answer by OmarAlhaddad · Jun 19, 2013 at 11:02 PM
If you wanna do FindChild(), you gotta go through the whole hierarchy like so: FindChild("globalMove01/joints01/..etc../TargetLookAt")
What i would do though, if the child you want is part of the prefab, you can just create a public transform variable and drag it to it, away from all this nonsense!
Edit: wanted to explain why the rest of your code is not working! its because the root has only one child like you mentioned, and that child has another child which has another child (but to the root there is only one).
Well, actually, I'd like to have a script, that takes a GameObject collects all the data needed automatically. So, I can't just make a public variable.
So, there are really no built in methods to look through the whole hierarchy?