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).
@oliver-jones have you tried to get the transform with the generic version of that function?
Transform[] _transforms = GetComponentsInChildren<Transform>();
Notice that you will get also the parent object with this query.
Hello, this appears to work fine. However, not only does it take into account the parent Transform. It also includes all sub children of the children. How do I make it so it doesn't include the parent, and sub-children?
Thanks.
public List<Transform> transformList;
foreach (Transform item in gameObject.transform)
{
transformList.Add(item);
}
You could just use a foreach and transform list.
Answer by Bunny83 · Dec 09, 2016 at 02:12 PM
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);
// ...
}
Answer by Ralp7 · Dec 09, 2016 at 02:27 PM
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>();
Danger! This will return the current object as well as any transforms lower down the hierarchy.