How to change material color during runtime in Unity

Many times, game developers code the response of an action in color. For example, the player turns red when it gets hit by an enemy. In this tutorial, we will see how to change the color of your gameobject using code during runtime.

What we will learn in this tutorial

  • How to access the renderer attached to your gameobject.
  • How to set the color of your game object.

Let’s take a simple scene with a cube.

Create a new material by right clicking on the project window>create>Material.

Assign the color of the material to black in the inspector.

Drag and drop the material onto the cube in your scene.

Now your scene should look as below.

Unity scene view with a black cube

Select the cube in Hierarchy window and you should see a Mesh renderer attached to the cube.

We will access this Mesh renderer and change the color using a script.

Add a script called Color_change to the cube.

Copy and paste the code below to change the color from black to red when the game starts.

using UnityEngine;

public class Color_change : MonoBehaviour
{
    Renderer col_rend;
    // Start is called before the first frame update
    void Start()
    {
        col_rend=GetComponent<Renderer>();
        col_rend.material.color=Color.red;
        
    }

}

This will instantly change the color from black to red. If you want it to change slowly from one color to another color you can use Unity lerp. Here is the sample code

using UnityEngine;

public class Color_change : MonoBehaviour
{
    Renderer col_rend;
    float timer=0;
    // Start is called before the first frame update
    void Start()
    {
        col_rend=GetComponent<Renderer>(); 
    }

    void Update()
    {
         col_rend.material.color=Color.Lerp(Color.black,Color.red,timer/5);
         timer+=Time.deltaTime;
    }

}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.