Change Material on Child Objects Upon Collision

I’m trying to change the material on a game object and its children when it receives a collision. With the current setup I have (below), the game object’s material changes successfully but the children’s do not. Can anyone tell me what needs to be changed or fixes I might try?

public Material demagedMaterial;
public Renderer childColor;

void Start() 
{
	childColor = GetComponentInChildren<MeshRenderer>();
}

void OnCollisionEnter(Collision collision)
{
    gameObject.GetComponent<MeshRenderer>().material = demagedMaterial;
    childColor.material = demagedMaterial;
}

That error is the difference between

Getting first found child…

childColor = GetComponentInChildren<MeshRenderer>();

…and getting all found children

childColors = GetComponentsInChildren<MeshRenderer>();

This is what your code should be changed to:

public Material demagedMaterial;
 public Renderer[] childColors;
 
 void Start() 
 {
     childColors = GetComponentInChildren<MeshRenderer>();
 }
 
 void OnCollisionEnter(Collision collision)
 {
     gameObject.GetComponent<MeshRenderer>().material = demagedMaterial;
     foreach(Renderer color in childColors) {
          color.material = demagedMaterial;
     }
 }

Note that the following lines were changed:

public Renderer childColor;

childColor = GetComponentInChildren<MeshRenderer>();

childColor.material = demagedMaterial;

Hopefully this helps.

Why do you do:

void Start() 
 {
     childColor = GetComponentInChildren<MeshRenderer>();
 }

childColor is not a direct reference to the child renderer ? if it is you are trying to get the material from a null object, if it is not, make one, GetComponentInChildren is slow, way better to have a direct reference to the object if you can.

Also use Renderer instead of MeshRenderer.