Return array of transform

Hello, I’m currently coding a function which will return a array of children.
But I can’t figure out how to return an array of children.
This is the code I have so far:

    //Find multiple children
    Transform[] FindChildrens(Transform parent)
    {
        foreach (Transform child in parent.transform)
        {
            return child;
        }
        return null;
    }

The thing wrong with your approach is that you are returning a single element, not an array.

As @Bunny83 pointed out in the comments, you could get the transform’s children array by simply calling:

parent.Cast<Transform>().ToArray(); 

But doing so would generate a lot of garbage. If you need an efficient way to get the children array you could get it by using the GetChild() method in a for loop.

 Transform[] FindChildrens(Transform parent)
 {
     //Declaring an array the size of the number of children
     Transform[] children = new Transform[parent.childCount];
     for (int i = 0; i < children.Length; i++)
     {
         //populating the array
         children *= parent.GetChild(i);*

}
//returning the array. If there is no children it will be an empty array instead of null.
return children;
}

This is probably the way to go:

GameObject parentObject;
Transform[] childernTransforms = new Transform[parentObject.transform.childCount];

for (int i = 0; i < parentObject.transform.childCount; i++) {
	childernTransforms  *= parentObject.transform.GetChild (i);*

}
And thats all. Hope it helps :slight_smile: