0
0
Unityframework~5 mins

Material properties in Unity

Choose your learning style9 modes available
Introduction

Material properties let you change how objects look in your game. You can make things shiny, rough, or colorful.

When you want to change the color of a game object during gameplay.
To make an object look shiny or matte by adjusting its smoothness.
When you want to add textures or patterns to surfaces.
To control transparency or glow effects on objects.
When you want to animate material changes, like fading or flashing.
Syntax
Unity
Material material = GetComponent<Renderer>().material;
material.SetColor("_Color", Color.red);
Color currentColor = material.GetColor("_Color");
Use the exact property name as defined in the shader, like "_Color" for the main color.
Always get the material from the Renderer component to access its properties.
Examples
This changes the object's color to blue.
Unity
Material mat = GetComponent<Renderer>().material;
mat.SetColor("_Color", Color.blue);
This reads how shiny the material is.
Unity
Material mat = GetComponent<Renderer>().material;
float smoothness = mat.GetFloat("_Glossiness");
This makes the material very shiny.
Unity
Material mat = GetComponent<Renderer>().material;
mat.SetFloat("_Glossiness", 0.8f);
Sample Program

This script changes the object's color to green when the game starts and prints a message in the console.

Unity
using UnityEngine;

public class ChangeMaterialColor : MonoBehaviour
{
    void Start()
    {
        Material mat = GetComponent<Renderer>().material;
        mat.SetColor("_Color", Color.green);
        Debug.Log("Material color changed to green.");
    }
}
OutputSuccess
Important Notes

Changing material properties at runtime creates a unique copy of the material for that object.

Use sharedMaterial if you want to change the material for all objects using it, but be careful as it affects all instances.

Check the shader documentation for the correct property names to use with SetColor, SetFloat, etc.

Summary

Material properties control how objects look in Unity.

You can change colors, shininess, and textures by accessing these properties.

Always get the material from the Renderer component before changing properties.