How to change material color during runtime using script 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.

Free Unity asset banner

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.

You can also use the SetColor function of Unity to change the color. Here is the syntax of how to use SetColor.

using UnityEngine;

public class color_change : MonoBehaviour
{
    Renderer ren;
    // Start is called before the first frame update
    void Start()
    {
        ren=GetComponent<Renderer>();
        ren.material.SetColor("_Color",Color.red);
        
    }

    
}

You can use RGB values in place of giving the color name if you have some specific color in mind. The RGB values has 4 components. The first 3 are the R,G and B values and the 4th one is the alpha that decides on the transparency.

Let’s give a vector4 as the input to the SetColor.

Here is the sample code

using UnityEngine;

public class color_change : MonoBehaviour
{
    Renderer ren;
    // Start is called before the first frame update
    void Start()
    {
        ren=GetComponent<Renderer>();
        ren.material.SetColor("_Color",new Vector4(1,0,0,1));
        
    }

    
}

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.