Changing material color - without instancing
Hi.
I am having some issues with changing the color of a material at runtime. When i do, it makes a new instance of the old material and changes the color of that. That is not what i want. I want to change the color of the actual material.
These are some of the things i have tried (simplified because i use a lot of arrays)
Obj.GetComponent(Renderer).sharedMaterials[i].color = Color.Red;
Obj.GetComponent(Renderer).sharedMaterials[i].SetColor("_Color", Color.Red);
Obj.GetComponent(Renderer).materials[i].color = Color.Red;
Obj.GetComponent(Renderer).materials[i].SetColor("_Color", Color.Red);
Every one of those, creates a new instance of the material, instead of changing the material like i ask for.
I know that i can create a Material variable, and set it in the inspector to the right material, and if i do any one of those lines on that variable, it will change the material, not make a new instance of the material. But i have tonnes of materials, and want it to work dynamically, so i dont want to do that.
How do i get around the problem?
Answer by EnJenGames · Oct 09, 2017 at 07:51 AM
I figured it out but will leave it here for others who have the same problem.
The problem for me, was that i had a for loop around the statements
for (var i = 0; i < Obj.GetComponent(Renderer).materials.Length; i++)
That was what created the instancing. Changing that to .sharedMaterial instead of .material, fixed the problem.
Your answer
![](https://koobas.hobune.stream/wayback/20220612140607im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Detect Color in If Statement 0 Answers
Accessing ARKit Camra colors 1 Answer
Transparent texture color? 0 Answers
Why do my materials look so different after HDRP upgrade? 0 Answers