- Home /
how to dynamically change materials of the object?
i know how to make materials in the inspector, but i dont now how to dynamically apply them to objects, i know this should be easy, but i am beginner...so any idea or example will be appreciated!
thanks!
Answer by fherbst · Oct 29, 2010 at 07:34 PM
Each gameObject which has a material also has a Renderer component, which can be accessed via scripting:
// Set main color to red
renderer.material.color = Color.red;
One thing you should know is that there is a difference between renderer.material
and renderer.sharedMaterial
: if you change the sharedMaterial
, all objects with this material applied change as well; if you change material
, Unity creates a copy of the material and thus applies the changes only to the object where you did the changes.
So, if you have a blue material on two cubes, and you use the code above on one of them, you end up with a red and a blue cube. If you use renderer.sharedMaterial
instead, both of them turn red. (This took me some time to find out, thus my in-depth explanation :D)
You can find more information on the Renderer component and materials in the scripting manual.
Your answer
![](https://koobas.hobune.stream/wayback/20220613081310im_/https://answers.unity.com/themes/thub/images/avi.jpg)