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!

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.