-1

I'm creating a game similar to the colour switch game, I've created this script to generate a random colour combination out of 8 colours. I've split my wheel into 4 parts. I want each part to have a different colour when I press the button, however, after many attempts, I'm still getting my issue of two or more parts having the same colour. Can this be done?

A gif to demonstrate: enter image description here

(In the example, I click the button 5 times, in two cases, the same colour repeated twice, aka the purple and the pink.)

My code:

 public SpriteRenderer[] colorWheels;
 public Color[] colorcombination;

public int uniqueRandomInt(int min, int max)
{
    int result = Random.Range(min, max);

    if(result == lastRandomNumber) {

        return uniqueRandomInt(min, max);

    }
    
    lastRandomNumber = result;
    return result;
}

public  void switchColour()
{
    for(int i = 0; i < colorWheels.Length; i ++)
    {
      colorWheels[i].material.color = RANDcolorcombination[uniqueRandomInt(0,8)];
    }
}

Thank you!

wasicool2
  • 193
  • 1
  • 3
  • 15
  • you want to have four colors selected (different) from a selection of 8 colors? – Frenchy Dec 13 '20 at 19:55
  • yeah, that's what I want to happen – wasicool2 Dec 13 '20 at 19:57
  • So either remove colours picked or reject selection choice if it’s already in the picked list – BugFinder Dec 13 '20 at 20:01
  • why would I want to remove the colours? I want to have the different colour combinations with each button clicked, but I don't want to get rid of any colours. – wasicool2 Dec 13 '20 at 20:05
  • so the first button click could be blue, purple, yellow and red, then the next button click could be red, pink, green and purple (which is still good), but like for the third button click (as an example) I don't want red, red, yellow, blue. (as red is repeated) – wasicool2 Dec 13 '20 at 20:08

1 Answers1

1

Sounds like what you actually would like is randomize the colors for each button click and then chose 4 colors from it:

private System.Random random = new System.Random();

public  void switchColour()
{
    // Is shuffled but it is sure that it still contains the same elements
    var randomizedColors = colorcombination.OrderBy(c => random.Next()).ToArray();

    // You can now simply select the first 4 values from the shuffled array 
    for(int i = 0; i < colorWheels.Length; i ++)
    {
      colorWheels[i].material.color = randomizedColors[i];
    }
}

This assures that each selected color is unique for this click. It is very unlikely but can and with enough clicks will still happen of course that a complete set of 4 colors occures twice ;)

derHugo
  • 83,094
  • 9
  • 75
  • 115