- Home /
How may I get the children (direct and dependents) of a game object?
Currently I am using Unity for university research purposes, and I am familiar with C# and Unity. In my project, I have a Robot in the hierarchy, and this Robot has many children, and children has their own children. like the following:
Robot>>Cabin/CounterWeight/BoomPivot>>Boom1/Boom2>>StickPivot>>Stick>>BucketPivot>>Bucket
Those with "Pivot" at the end of their name, is assigned with the tag called, "RobotPart". I am looking for a piece of code that automatically search in the children of the "Robot" and find those with the tag "RobotPart". Is there any way to do that?
Finally I want to have access to the properties of those children and control them if necessary. Thanks. strong text
While not a direct answer to your question, one solution is to put a unique component on all RobotPart game objects. Then you can use GetComponentsInChildren() to find all the game objects. Note that GetComponentsInChildren() with 'Transform' as the component will find all Transforms (and therefore all game object) in the hierarchy.
Answer by smoggach · Aug 19, 2014 at 09:30 PM
You can use GameObject.FindGameObjectsWithTag("RobotPart").
Answer by Kiwasi · Aug 19, 2014 at 09:37 PM
Best way would be GetComponentsInChildren.
Edit: Just reread your question. Another way would be to do a recursive search. Pseudo code as follows. Note this search could be long an expensive on a complicated hierarchy. Save your project before running too. Recursive functions are notorious for causing infinite loops if mistakes are made.
List<GameObject> RobotParts = new List<GameObject>();
void SearchForParts(Transform current){
foreach (Transform child in current){
if(child.tag = "RobotPart"){
RobotParts.Add(child.gameObject);
}
SearchForParts(child);
}
}
Your answer
Follow this Question
Related Questions
c# Adjust In-Game audio 1 Answer
Randomly Generated Objects 1 Answer
Structs in C# Question 3 Answers