- Home /
Cannot cast form source type to destination type?
Trying to get child transforms, store them in a transform array.
childTransforms : Transform[];
thisTransform : Transform;
childTransforms = thisTransform.transform.GetComponentsInChildren(Transform);
Do I need to just use GameObject for thisTransform?.. Edit:nope that doesnt work either.
Answer by Dave-Carlile · Oct 25, 2013 at 02:25 AM
GetComponentsInChildren returns a Component
array, not a Transform
array.
e.g.
Component[] components = transform.GetComponentsInChildren(Transform);
I went ahead and used :
childTransforms = thisTransform.transform.GetComponentsInChildren(Transform)as Transform[];
Answer by clunk47 · Oct 25, 2013 at 02:32 AM
Don't need to define thisTransform, all you need to use is 'transform' for that. You also need to use var... Just to clean things up, I'd make a Generic List instead of array.
#pragma strict
import System.Collections.Generic;
var children : List.<Transform> = new List.<Transform>();
function Start ()
{
for(var t in transform)
children.Add(t);
for(var c in children)
print(c.name);
}
I'm using built in array in this case because the variables will always be the same. Usually I do use a List though.
But keep in $$anonymous$$d that GetComponentsInChildren will return all Transforms even deeply nested childs since it searches through the transform-tree recursivly. Also only enabled gameobjects will be included.
Iterating through the IEnumerable of transform:
for(var t in transform)
// t...
will only return direct childs and regardless of their active states.
Son of a biscuit! " Also only enabled gameobjects will be included". This is why I'm now getting a different error. Thanks! :) I was wondering why the heck it didn't know what I was referencing.
I forgot that Unity added an optional parameter which allows to search for inactive objects as well ^^
Just pass true as second parameter.
GetComponentsInChildren(Transform, true)
See the docs