- Home /
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;
}
Do you have multiple children? GetComponentInChildren only gets the first (depth first search) component, you should use GetComponentsInChildren (note the additional "s") and iterate through them to set the material for all children.
I changed it to GetComponentsInChildren and it actually produced this error:
error CS0029: Cannot implicitly convert type UnityEngine.$$anonymous$$eshRenderer[]' to
UnityEngine.Renderer'
(I got a similar one when I changed the variable to be a $$anonymous$$eshRenderer type as well, so doesn't seem like that's the issue.)
Answer by wesleywh · Jun 28, 2016 at 04:32 AM
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.
Hi- thanks for the advice, but this produced the same error I mentioned on the post above.
That's because he made a small mistake. The variable definition should be:
public $$anonymous$$eshRenderer[] childColors;
not
public Renderer[] childColors;
Answer by EDevJogos · Jul 02, 2016 at 09:32 PM
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.
Your answer
Follow this Question
Related Questions
Trail prefab as the child of existing object. 1 Answer
collision on child only returns parent object ? 1 Answer
C# Ignore Collision Trigger From Child 2 Answers
Distribute terrain in zones 3 Answers
Attaching objects on collision 1 Answer