Find children of object and store in an array

How do I find the children of an object, and store them in an array?

I have a wall, with 4 points. I wan’t to be able to access these points, but in order to do that I need to have them in an array.

I use C#

IList<Transform> GetChildren(Transform transform) { return Enumerable.Range(0, transform.childCount) .Select(x => transform.GetChild(x)) .ToList(); }

3 Answers

3

For a one line method to get the array

Transform[] children = GetComponentsInChildren<Transform>();

Transform is also enumerable. So you can avoid the array altogether with:

foreach (Transform child in transform){
    // Do something to child
}

Thank you for your answer, I works.... Kinda. When I use this 1 line method, I don't get the children only. I get the parent as well! Why??? My code: public GameObject test; public Transform[] points; void Update(){ points = test.GetComponentsInChildren<Transform>(); }

Here is the doc description: Returns all components of Type type in the GameObject or any of its children. If you want to remove the parent: var children = Array.FindAll(GetComponentsInChildren<Transform>(), child => child != this.transform); but I think the parent is always the first one so you could start iteration from second index (1). But I am not 100% sure about that.

Huh, learned something new today. Thanks for the heads up.

What is the: child => child != this.transform); ??

[lambda expression][1] Its a weird, but very powerful C# language feature. [1]: http://msdn.microsoft.com/en-us/library/bb397687.aspx

Based on your questions I’ve seen here, you’d really benefit from spending an afternoon in the Learn Unity area of the website, where lots of tutorials address a ton of beginner’s questions while teaching good practices.

You probably want this:

Transform[] children = new Transform[transform.childCount];
for (int i=0; i<transform.childCount; i++) {
    children*=transform.GetChild(i);*

}

So with this, I could do something like: send a raycast and check if I hit a certain object. If I hit that object, then get and store the objects children in an array?

Simple and working solution

List children = new List();

void Start()
{
  foreach (Transform t in transform)
   {
     children.Add(t.gameObject);
   }
}