- Home /
Finding a child without knowing its name?
Question, how do I find a child of a specific parent (Which is stored as a gameobject) without knowing its name? (Theres only 1 child)
I tried using tags with this:
tocolor = hairmodel.FindGameObjectWithTag("hair");
But it gave me the error:
Static member `UnityEngine.GameObject.FindGameObjectWithTag(string)' cannot be accessed with an instance reference, qualify it with a type name instead
How do I get this done?
Answer by aldonaletto · Jul 12, 2012 at 05:44 AM
There's an undocumented function (Transform.GetChild(n): Transform) that gets the children by index:
tocolor = hairmodel.GetChild(0);
Notice that hairmodel and tocolor in this case should both be Transform variables - GetChild is a function of the Transform class, and also returns a Transform.
Using undocumented functions is generally a risky practice, because they may simply disappear in new Unity versions (but this specific function is used in the Unity's FPS Tutorial, in the PlayerWeapons.js script).
If you don't want to use an undocumented function, that's a somewhat stupid alternative that can work when there's only one child (javascript):
for (var ch in hairmodel){
tocolor = ch;
}
or, in C#:
foreach (Transform ch in hairmodel){
tocolor = ch;
}
Once again, I'm assuming that hairmodel and tocolor are Transform variables; if both are GameObjects, use this:
foreach (Transform ch in hairmodel.transform){
tocolor = ch.gameObject;
}
I have been trying to solve this for like two days. Thank you Aldo.
Your answer
Follow this Question
Related Questions
Access a child from the parent or other gameObject. 2 Answers
GameObjectWithTag Child 1 Answer
Find a child with a name, how to?? 5 Answers
How to call a child by tag or name 1 Answer