Reputation: 11325
In this case there are two walls. Each wall have 4 children and each of the 4 children have a cube child that I want to color.
This code color only one of the 4 children of each wall and not all the 4 :
private void ColorWalls()
{
for (int i = 0; i < walls.Count; i++)
{
if (randomColors)
{
walls[i].transform.GetChild(0).transform.GetChild(0).GetComponent<Renderer>().material.color
= GetRandomColour32();
}
else
{
walls[i].transform.GetChild(0).transform.GetChild(0).GetComponent<Renderer>().material.color = colors[i];
}
}
}
How can I loop more deep to color all the 4 cubes of each wall ?
Upvotes: 0
Views: 935
Reputation: 87
The most easy way is GetComponentsInChildren<Renderer>
. But in case that there are Renderer
other than wall would be in the hierarchy. There are at least 2 ways to do this:
Then use GameObject.FindGameObjectsWithTag
to get all the gameobjects.
MonoBehaviour
to wall gameobject, let us call it Wall
.Then you can call GetComponentsInChildren<Wall>()
at the root gameobject.
Upvotes: 1
Reputation: 351
https://answers.unity.com/questions/799429/transformfindstring-no-longer-finds-grandchild.html
This will help you find the deep child of a transform. But if it is just the components that you're looking for without the need for the hierarchy info, you can go with what's been suggested in @rootpanthera's comment.
Upvotes: 1