Switch color has same color c# unity

Hai, i made some balls (spheres) on unity3d and i changed their color using random color. But, when i run the program, sometimes i got same color on both sphere.

How do i prevent this? Basically when the color already assigned in the object, that color won’t be generated again.

Here is the code that i made for color of the balls (spheres)

public virtual void ColorChanger()
        Color newColor = new Color(Random.value, Random.value, Random.value, 1.0f);
        transform.renderer.material.color = newColor;

and here is the image that show the same color on both balls (spheres)


Maybe at some point you assign the same material to both spheres?

Do they share the same material? Perhaps try having a unique material for each one.

Hi Fuhans,

It is highly unlikely, but not impossible to get 2 similar random colors in a row. What you could do is have a List of possible colors that you pick from, removing colors as you go to ensure the same will not be drawn twice. Keep a copy of the List somewhere to restore your pool of colours at will.

Also, random rgb colors aren’t great: they tend to be greyish brownish. Better to use HSV color space, see this awesome post with very much usable code : http://forum.unity3d.com/threads/12031-create-random-colors

If your method is overriden, you need to make sure that you call base.ColorChanger() at the beginning of your overriden method and that you don’t change this value after.