- Home /
Changing Color of Secondary Material in Materials Array
Hi Friends,
I'm having trouble doing programmatic updates to materials when I've got multiple materials on a mesh. I am consistently able to update the material in the [0] position of the materials array, but I'm not able to get the material in materials[1] to update regardless of what I try.
I've got a mesh with two section that get two different materials, which looks more or less like this:
The definition of this mesh is like this:
If I execute the following code in a script's Start() function, the color of the metal material turns red properly at the start of runtime, but the glow material stays yellow:
GetComponent<Renderer>().materials[0].color = Color.red;
GetComponent<Renderer>().materials[1].color = Color.red;
The upvoted answer from this other question (https://answers.unity.com/questions/124794/how-to-replace-materials-in-the-materials-array.html - this is from 2011, so likely things have changes since then) suggests that the materials in the materials array are copies, and so the solution is to replace the entire array, which I've tried doing, but the end-result is identical - only the material in position [0] changes, the material in position [1] is unchanged.
Material[] temp = GetComponent<Renderer>().materials;
temp[0].color = Color.red;
temp[1].color = Color.red;
GetComponent<Renderer>().materials = temp;
I've been scratching my head at this one, and will continue checking, but has anyone else run into this?
Answer by Martin_Gonzalez · Mar 29, 2018 at 07:16 PM
I've tried this. Just to be sure that there is no other issues between.
Create a Cube in the scene
Create a material in your project tab
To the Cube material array in Renderer component add the created material
Add the following script into the cube and hit play and check if the material chage it color.
using UnityEngine; public class MaterialTest : MonoBehaviour { private void Start() { var materials = GetComponent<Renderer>().materials; foreach (var material in materials) { Debug.Log(material); } materials[1].color = Color.red; } }
It worked for me
Sorry for the delay in getting back on this; this worked for me, and while running this example code I discovered that the issue with my original test-cases was that Unity wasn't re-compiling the C# script I was editing, so even though I was changing the C# file the actual class was remaining static to a version that changed only the first material.
After testing properly, simply calling "GetComponent().materials[1].color = Color.red" directly works as expected, so all issues were co$$anonymous$$g from my script not re-compiling. I fixed that in my unity project, so we're all good now. Thanks so much!