- Home /
How to use GetComponentsInChildren ( Example :- to print all children gameobject'sname )
i started learning editor scripting....i streaked while my experimentation. kindly anyone help me to understand GetComponentsInChildren.
my project structure is like this
i want to print the names of all child(Top to Bottom) one by one...including Bottom (inactive child)
my code attached to Top is
public class Example : MonoBehaviour {
public GameObject[] obj;
void Awake(){
obj = GameObject.GetComponentsInChildren<GameObject>();
foreach(GameObject ob in obj)
{
Debug.Log(ob.name);
}
}
}
i tried and failed with this code...It will be very helpfull if anyone help me to get it :)
Answer by gjf · Jul 09, 2014 at 10:05 AM
look for the Transform
component
using UnityEngine;
using System.Linq;
public class Example : MonoBehaviour
{
public Transform[] obj;
void Awake()
{
obj = GetComponentsInChildren<Transform>(true);
foreach (var ob in obj.Where(ob => (ob != transform)))
{
Debug.Log(ob.name);
}
}
}
the true
in the GetComponents
call will get active AND inactive.
can u explain how .Where(ob => (ob != transform) work...im new to program$$anonymous$$g...
is => stands for lessthan or equal operator there?
it's LINQ
- the following does the same:
foreach (var ob in obj)
{
if (ob != transform)
{
Debug.Log(ob.name)
}
}
it checks to see whether the child object is actually the parent since GetComponentsInChildren
returns that too.
apologies for complicating things for you.
Answer by papabooish · Jul 09, 2014 at 10:30 AM
GameObject isn't a component, it's a container for components, so you can't search for it (as far as I know). Instead as said search for the transform component, since all GameObjects contain a transform (In fact the whole object hierarchy is located on the transform component)
void Awake() {
bool includeInactive = true;
Transform[] ts = GetComponentsInChildren<Transform>(includeInactive);
foreach(Transform t in ts)
Debug.Log(t.name);
}
This should find all Transforms, including the Transform of the GameObject that the script is attached to and print the name.
Answer by ruudlenders · Jul 09, 2014 at 10:30 AM
GetComponentsInChildren
isn't the best way to loop through a parent-child structure. GetComponentsInChildren
search for specific components, but a game object's name is not part of any component. For your specific example, I would do this:
void Awake()
{
PrintNames(this.transform);
}
void PrintNames(Transform parent)
{
Debug.Log(parent.name);
foreach (var child in transform)
{
PrintNames(child);
}
}
Your answer
Follow this Question
Related Questions
The name 'Joystick' does not denote a valid type ('not found') 2 Answers
How can I change the icon of a script within the Project View? 5 Answers
Edit a inspector variable from editor script.(its not saving) 1 Answer
Updating object on inspector value changes in editor 1 Answer
How to get notification of moving a GameObject in the hierachy when editing the scene? 1 Answer