Random Color Range Without Duplicates,Random Color Range Without Duplicates?

My code Randomly picks a color and changes the color of my player,
I want it to do the same thing but never pick a duplicate color
For Example now:
Yellow, Yellow, Blue, green, green, orange
But I don’t want it to repeat the same color twice!
How would I do this?

,

My code Randomly changes the color of my player but I don’t want it to ever duplicate the same color!
How would I do this?

@mmfallentine
The eassiest solution is to use a list instead of an array, and each time you get the color, you remove that color from the list, so the next time you try to get a ramdom color, the previous one won’t be included. I haven’t tested this, but it should work.

  • So, when you create the variable, instead of using Color colors to create the array, use List < Color> colors (you hace to use the libray System.Collections.Generic, so at the begining if you don’t have it add using System.Collections.Generic;)

  • In the Awake method, at the begining put colors = new List< Color>() to initialice te variable, then instead of colors[0] = Color.Red, colors[1] = Color.Green…,to add a color, use colors.Add(Color.Red), colors.Add(Color.Green)…, and then call the corroutine: StartCorroutine(“ColorChangeStart”);

  • Finally, in your ColorChangeStart corroutine put the following lines (first get the random index, then change the color, and then remove that color from the list):

    IEnumerator ColorChangeStart ()
    {
    while (colors.Count > 0)
    {
    SpriteRenderer spriteRenderer = GetComponent();
    int randomInt = Random.Range (0, colors.Count);
    spriteRenderer.material.color = colors[randomInt];
    colors.Remove(randomInt);
    yield return new WaitForSecond (1);
    }
    Debug.Log (“No more colors”);
    }