- Home /
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:
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.
Answer by $$anonymous$$ · May 18, 2015 at 10:21 AM
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:
http://docs.unity3d.com/ScriptReference/Component.GetComponentsInChildren.html
Ah, much thanks. I hadn't even heard of the GetComponentsInChildren method. But its all sorted now, So thanks for bringing it up.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Jittery world around stationary character 1 Answer