- Home /
Change Color of Material in Loop
I have a for loop which creates an Object for each of its iterations. Each Object is supposed to have a Color, randomly selected from my Color array. Even though it should, it does not set another Color for each iteration of the Loop but rather takes a random color once and then applies it to every Object, completely ignoring the following color changes.
public Material material;
private Color[] colors = new Color[] {Color.red, Color.blue, Color.yellow, Color.white, Color.magenta, Color.green };
private void Start(){
material.color = colors[Mathf.FloorToInt(Random.Range(0, colors.Length))];
GameObject quad = GameObject.CreatePrimitive(PrimitiveType.Quad);
quad.GetComponent<Renderer>().material = material;
}
Comment
Best Answer
Answer by ilagef · Jul 18, 2020 at 11:39 AM
You need to create a different materials for each gameObject.
Since all the Gameojects has the same material, your set them all to the same color.
Try this:
private void Start()
{
Material material = new Material(Shader.Find("Specular"));
material.color = colors[Mathf.FloorToInt(Random.Range(0, colors.Length))];
GameObject quad = GameObject.CreatePrimitive(PrimitiveType.Quad);
quad.GetComponent<Renderer>().material = material;
}