- Home /
C# Specifying which Children to add to the Array
Hi everyone, is there a way to get GetComponentsInChildren(); to specify which children to add to someTransformArray? I want to add some of the gameobject's children to the array but not all of them.
Public Transform[] someTransformArray;
void Awake(){
someTransformArray = GetComponentsInChildren<Transform>();
}
Get components in children will return only those game objects who have the specified component attached. At that point you have to scrub the list based on some other criteria.
I don't know what you mean, what other options. You get all the components, and filter the ones you don't want. That's what you're saying you want to do. Verbalizing it helps sometimes to realize how trivial a problem is. If you shared what you want to filter out then you might get more help.
Answer by BlueRaja_2014 · Jun 26, 2013 at 10:27 PM
If I understand correctly, you want to filter the return values from GetComponentsInChildren()
to only select the values of type Transform
and set it equal to an array?
Try this:
someTransformArray = GetComponentsInChildren().OfType<Transform>().ToArray();
It reads almost like English; gotta love LINQ :)
Note: You may need to include using System.Linq
to use `OfType()`.
@iwaldrop Does he want a list of the Transform
-property values from each component, or a list of components which are of type Transform
? Those are two different questions.
I answered the latter; the former can be done withGetComponentsInChildren().Select(o => o.Transform).ToArray();
No I simply want to specify which children the array picks. There are some children in my gameobject that I don't want to add to the array.
Add a .Where((x)=> x == somethingYouWant) to your LINQ query.
@DangerousBeans
That is also a one-liner in LINQ. For example, to get all the components with positive X-value:GetComponentsInChildren().Where(o => o.X > 0).ToArray();