- Home /
Find children of object and store in an array
How do I find the children of an object, and store them in an array?
I have a wall, with 4 points. I wan't to be able to access these points, but in order to do that I need to have them in an array.
I use C#
Answer by Kiwasi · Oct 26, 2014 at 07:20 AM
For a one line method to get the array
Transform[] children = GetComponentsInChildren<Transform>();
Transform is also enumerable. So you can avoid the array altogether with:
foreach (Transform child in transform){
// Do something to child
}
Thank you for your answer, I works.... $$anonymous$$inda. When I use this 1 line method, I don't get the children only. I get the parent as well! Why???
$$anonymous$$y code:
public GameObject test;
public Transform[] points;
void Update(){
points = test.GetComponentsInChildren<Transform>();
}
Here is the doc description:
Returns all components of Type type in the GameObject or any of its children.
If you want to remove the parent:
var children = Array.FindAll(GetComponentsInChildren<Transform>(), child => child != this.transform);
but I think the parent is always the first one so you could start iteration from second index (1). But I am not 100% sure about that.
Huh, learned something new today. Thanks for the heads up.
Its a weird, but very powerful C# language feature.
Answer by AlwaysSunny · Oct 26, 2014 at 01:46 AM
Based on your questions I've seen here, you'd really benefit from spending an afternoon in the Learn Unity area of the website, where lots of tutorials address a ton of beginner's questions while teaching good practices.
You probably want this:
Transform[] children = new Transform[transform.childCount];
for (int i=0; i<transform.childCount; i++) {
children[i]=transform.GetChild(i);
}
So with this, I could do something like:
send a raycast and check if I hit a certain object. If I hit that object, then get and store the objects children in an array?
Answer by mzr_developer · Jul 09, 2019 at 09:05 AM
List<GameObject> children = new List<GameObject>();
void Start()
{
foreach (Transform t in transform)
{
children.Add(t.gameObject);
}
}
Your answer
Follow this Question
Related Questions
Find closest object with tag 1 Answer
Remove first element of array 1 Answer
Find closest transform 1 Answer
Closest array element 1 Answer
Add one on local z axis 3 Answers