How to change the color of a child through its parent?

Hello, good evening.
I was wondering if it is possible to change the color of a childs mesh along with its parent. I am currently making an RTS (Or rather, trying to.) and when I select an object which is parented to another mesh the parented mesh changes color but leaves the children unaffected. Here is the code used to change its color:

using UnityEngine;
using System.Collections;

public class Unit : MonoBehaviour {

	public bool selected = false;

	private void Update () {
		if (renderer.isVisible && Input.GetMouseButton(0)) {
			Vector3 camPos = Camera.main.WorldToScreenPoint(transform.position);
			camPos.y = CameraSelect.InvertMouseY(camPos.y);
			selected = CameraSelect.selection.Contains(camPos);
		}
		if (selected) {
			renderer.material.color = Color.red;
		}else{
			renderer.material.color = Color.white;
		}
	}
}

And here is a picture of the parent and the children in the Hierarchy:

46569-capture.png

And here is the parent being selected (In red) and the children not:

Is it possible to see if the object is parented to anything and then get those game objects to change color? sorry again if this is a stupid question with a simple answer, thank you for your time.

1 Answer

1

Using gameObject.GetComponentsInChildren<>() you can get a list of all children Renderer components. You can then loop through and change the color of all the ones you want.

Check it out:

Ah, much thanks. I hadn't even heard of the GetComponentsInChildren method. But its all sorted now, So thanks for bringing it up.