N1ckGreek N1ckGreek - 20 days ago 4
C# Question

How to select which child component to get using GetComponentInChildren, when there are multiple child objects

How can I select from which child I want to get a component from using

.GetComponentInChildren
when I have multiple child objects?

With this code I get the
MeshRenderer
of the first child only.

selectedObj.GetComponentInChildren<MeshRenderer>().material.SetColor("_EmissionColor", Color.red);

Answer

If you know the unique name of the child object that has the component you are after, you can use transform.FindChild("nameOfChildObject") to find the specific child object you are looking for. So in your case you could say:

selectedObject.transform.FindChild("nameOfChildObject").GetComponent<MeshRenderer>().material.SetColor("_EmissionColor", Color.red);