- Home /
Renderer Materials not changing elements
Hello,
I have a simple script that changes the elements of a object. What is wrong this the following?
children.GetComponent<Renderer>().materials[0] = mat;
children.GetComponent<Renderer>().materials[1] = mat2;
The above doesn't change any mats nor does it throw an error. The blow does indeed work.
children.GetComponent<Renderer>().material = mat;
I've looked around the internet on a fix but I couldn't find anything that works.
Thanks.
Comment
Best Answer
Answer by Bonfire-Boy · May 07, 2019 at 04:15 PM
Renderer.materials returns a copy, so you're not working on the actual array here (see note on this page: https://docs.unity3d.com/ScriptReference/Renderer-materials.html ).
You need to do something like this...
Renderer r= children.GetComponent<Renderer>();
Material[] mats = r.materials;
mats[0] = mat;
mats[1] = mat2;
r.materials = mats; // this is the key - you need to set the renderers materials array to the one you've modified
Thanks you! Also put a space on the end of the page link i thought the link was not working at first.
Oh yeah, sorry about the link glad you worked it out. Have added that space.