Get all Child Transforms in Target

Hello,

I, for some reason cannot get this to work…

All I’m trying to do is to get all the Child Transforms that are present within a target and return them as an array. I have done and followed examples online, including the API, and I get errors.

This is how I have it right now. This gets the return method of the Transforms

//get all children on target object
Transform[] _children = (Transform[])_target.GetChildrenOfObject();

Return method:

public Transform[] GetChildrenOfObject(){

	Transform[] _transforms;
	_transforms = (Transform[])GetComponentsInChildren( typeof(Transform), true );
	return _transforms;
}

When I run this, I get the error : Cannot cast from source type to destination type. So I tried:

public Transform[] GetChildrenOfObject(){

	Component[] _transforms;
	_transforms = GetComponentsInChildren( typeof(Transform), _includeInactive );
	return _transforms as Transform[];

}

Which returns a Null…

What am I doing wrong here? (Might be worth mentioning that this code is for an Editor script - so it gets called in Editor Mode, and Play Mode).

Don’t use GetComponentsInChildren because it does exactly what you have described. It includes the parent as well as all component in any children, no matter how deeply nested.

The Transform class implements the IEnumerable interface. Unfortunately only the type-less version. Though a foreach loop can handle that directly:

foreach(Transform child in transform)
{
    // ...
}

The second way, if you want the childs in an array or list, is to use Linq.

// of course at the top
using System.Linq;

// as typed enumerable
IEnumerable<Transform> childs1 = transform.Cast<Transform>();
// as array
Transform[] childs2 = transform.Cast<Transform>().ToArray();
// as list
List<Transform> childs3 = transform.Cast<Transform>().ToList();

The third way, without using Linq would be to use childCount and GetChild:

int count = transform.childCount;
for(int i = 0; i < count; i++)
{
    Transform child = transform.GetChild(i);
    // ...
}

I don’t know what is wrong with your code but you can use generic version of GetComponentsInChildren function which works fine.

_transforms = GetComponentsInChildren<Transform>();