Daniel Lip
Daniel Lip

Reputation: 11325

How can I get to the children deep level?

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.

Children hierarchy

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

Answers (2)

Jennal
Jennal

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:

  1. add tag to wall gameobject.

enter image description here

Then use GameObject.FindGameObjectsWithTag to get all the gameobjects.

  1. add custom MonoBehaviour to wall gameobject, let us call it Wall.

Then you can call GetComponentsInChildren<Wall>() at the root gameobject.

Upvotes: 1

varunkaustubh
varunkaustubh

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

Related Questions