Home > OS >  How to assign random colors to a gameObject in unity?
How to assign random colors to a gameObject in unity?

Time:05-05

I have 3 colors ( Red, Green, and Yellow ), I want to assign random colors from these 3 colors to my Ball every time when My game starts or restarts after gameOver.

Thanks!

CodePudding user response:

Define the colors in the list and select them in the inspector.

public List<Color> Colors = new List<Color>();

private void ChangeColor()
{
    GetComponent<MeshRenderer>().material.color = Colors[Random.Range(0, Colors.Count)];
}

CodePudding user response:

Create a list or array with the colors, then use random.range() accordingly on that array in the Start method (or a custom method if you restart manually.) If every color should be guaranteed unique, use the singleton pattern to keep a common instance of that colors list and remove the used color every time it's taken.

  • Related