How to access all children of a transform in Unity Script ( Javascript )

Some things have changed in Unity 3.0, one of them is how to access the children of a gameObject. The Transform Component can have one or more children, but how can you access them ?

The answer seems trivial. Look it up in the docs, right here. Only that it gives an error :

BCE0022: Cannot convert ‘Object’ to ‘UnityEngine.Transform’.

After some search in the forums, in the Unity answers and #unity3d I found a solution (and spend 1 hour): I post it so you do not have to face the same frustration.

function Start()
{
	var myTrans:Transform[]  = gameObject.GetComponentsInChildren.() as Transform[];

	for (var child : Transform in myTrans )
	{
		//Do your stuff
	}

}

The above code will give you back all the children of a gameObject, regardless their nesting level.
Hope this helps :)

This entry was posted in Uncategorized by ippo. Bookmark the permalink.

Leave a Reply