- Home /
Assign multiple childs as gameobjects through script
I have an object with multiple children and a children's child. How would I go about accessing their gameObjects as different variables?
Answer by Horschty · Jun 03, 2018 at 07:13 PM
You want to get all the children and childrens children of a gameObject? If so, this should do it:
private List<GameObject> GetAllChildren(Transform t) {
List<GameObject> children = new List<GameObject>();
for(int i = 0; i < t.childCount; i++) {
var child = t.GetChild(i);
children.Add(child.gameObject);
children.AddRange(GetAllChildren(child.transform));
}
return children;
}
// Then to use it
void Start() {
var children = GetAllChildren(transform);
}
So now if I want to rotate a child, how would I do that.
By setting its transform.rotation. Look into the Quaternion class it has a lot of helper functions. For instance to set its rotation to 90 degrees around the Z axis: childGameObject.transform.rotation = Quaternion.Euler(0.0f, 0.0f, 90.0f); Which is the same as going to the inspector and setting Z rotation to 90.
Your answer
Follow this Question
Related Questions
How Should I Get a List of Child Objects 2 Answers
Get children of another object in hierarchy. 1 Answer
How to Access Components in Children of GameObject? 1 Answer
Why is the wrong child activated, although I have the right index? 1 Answer
using DrawMesh to draw all sub meshes and materials for a game object and children 1 Answer