How to have random and different colors on multiple objects with one material?

by Matthew Inglis   Last Updated December 25, 2016 08:05 AM

I want to have one material applied to multiple objects that has a random color on each object. How can I achieve this so that I don't need to use a different material for every object? This is in Unity 5 by the way.



Answers 1


You can change the color of the same material, on different objects, from script. Do the following:

  1. Create a materialand assign it to the target game object.

  2. Create a new C# script, and copy in the following code. Inside "parent" the objects whose color should change is placed in the unity editor.


using UnityEngine;
using System.Collections.Generic;

public class RandomColor : MonoBehaviour 
{
    public Transform parent;

    List<Transform> objectstoColor;

    void Start () 
    {
        objectstoColor = new List<Transform>();

        foreach (Transform item in parent)
        {
            objectstoColor.Add(item);
        }
    } 

    <summary>Method for changing the material color</summary>
    public void SwitchColors()
    {
        foreach (Transform item in objectstoColor)
        {
            Renderer rend = item.gameObject.GetComponent<Renderer>();
            rend.material.color = Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f);
        }
    }   
}

Creating material and game object Assigning the Script to any gameobject in the scene Calling the Method when button is clicked.

Shuvro Sarkar
Shuvro Sarkar
November 23, 2016 07:18 AM

Related Questions





Unity2D: Vector3.Lerp - smooth movement

Updated August 24, 2018 22:13 PM