How to get children from a Parent and not get the children of the children too
i have this code
GameObject AC = GameObject.Find(_parent); //Find the Constutiency object
Transform[] acs = AC.GetComponentsInChildren<Transform>();
i just need to get the child objects of the parent but the child objects too have children and those child objects of the child object are also grabbed.
i read this post link text
i have iterated through transform to get the children, is this the only way to do it ?
Answer by Remy_Unity · Mar 15, 2018 at 01:05 PM
Well, the answer was in the linked post :
GameObject AC = GameObject.Find(_parent); //Find the Constutiency object
foreach (Transform child in AC.transform)
{
//child is your child transform
}
Yeah but is this the only way to achieve this ? is there a simple way to just get children ? and not the childrens children too ?
Other way (if you want to store the children in an array), is to use the method mentioned by @donutLaserDev . Pretty similar to $$anonymous$$e.
And no, it's the only way to access direct children of an object : https://docs.unity3d.com/ScriptReference/Transform.html
Answer by donutLaserDev · Mar 15, 2018 at 01:06 PM
You can use this:
GameObject AC = GameObject.Find(_parent); //Find the Constutiency object
Transform[] acs = new Transform[AC.transform.childCount];
for (int i = 0; i < AC.transform.childCount; ++i) {
acs[i] = AC.transform.GetChild (i);
}
Answer by meat5000 · Mar 15, 2018 at 02:12 PM
Does childCount also count grandchildren? If it doesnt perhaps you can use the figure returned to iterate your list hopefully skipping all grandchildren.
I had another thought, perhaps if you just GetChild the First Child you can then use GetSiblingIndex to discover the children on the same level.
Never tried this, its just a concept.
childCount tells the number of immediate children only, it doesn't count the grandchildren.
Awesome. So its simple case of using that number to truncate the list.
Answer by Harinezumi · Mar 15, 2018 at 04:15 PM
If I understand it correctly, you want all the immediate child transforms of parent. In that case, this question seems to provide a solution.
If what you want is to get components only in the direct children then this forum thread seems to have the best solution (3 versions, towards the bottom). To summarize, iterate through the child transforms of parent's transform and put the components in a List.
Your answer
Follow this Question
Related Questions
Find a rigidbody's root parent then find its child by name 1 Answer
Problem with parent gameObject not where it should be after adding childs 0 Answers
Why my parent follows its child game object? 0 Answers
Following object (arrow) slides off of a object 1 Answer
Parent-Child axial reference problem 0 Answers