Changing object's material with script

Hello,

I’m quite new to Unity. I have a simple scene: a green cube. I’ve added simple gui script to create a menu with one button. I want the cube to change color to red, for example, when I press the button. How would I do that, please?

public Material redMaterial;
public Material greenMaterial;

....
if(GUILayout.Button("Change material color"))
{
renderer.material.color = Color.red;
}
if(GUILayout.Button("Change material"))
{
renderer.material = renderer.material == greenMaterial ? redMaterial : greenMaterial;
}

Slem,

Thank you for quick answer. It works great with colors, but I have an issue with materials. What if I already have redMaterial and greenMaterial in my assets, how should I reference to them?

the RedMaterial and GreenMaterial should be visible in the inspector when inspecting the cube that has the script. Just drag and drop the materials you want for red and green.

Thank you, now I understand how it works.