Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity - Get Random Color at Spawning

i have a little issue....i want to spawn Quads in my Scene and they all should have either red or green as Material. But the Random.Range function will only int´s, how could i solve it ??

void SpawningSquadsRnd()
    {
        rndColor[0] = Color.red;
        rndColor[1] = Color.green;

        for (int i = 0; i < 5; i++)
        {
            GameObject quad = Instantiate(squadPrefab, new Vector3(Random.Range(- 23, 23), 1.5f, Random.Range(-23, 23)), Quaternion.identity);
            int index = Random.Range(0, rndColor.Length);

            quad.gameObject.GetComponent<Renderer>().material.color = //Random.Range(0, rndColor.Length);
        }
    }
like image 600
Raycen Avatar asked Mar 05 '23 10:03

Raycen


1 Answers

If you want only red and green you can achieve it with a basic if and else structure like this:

    int index = Random.Range(0, 1);
    if(index == 1)
    {
        quad.gameObject.GetComponent<Renderer>().material.color = new Color(1, 0, 0);
    }
    else
    {
        quad.gameObject.GetComponent<Renderer>().material.color = new Color(0, 1, 0);
    }

If you want something better you can random a float between 0 and 1 and then Lerp between colors like this:

    float index = Random.Range(0, 1);
    quad.gameObject.GetComponent<Renderer>().material.color = Color.Lerp(Color.red, Color.green, index);

If you want to fully randomized the coloring you can also use this as well. However, it gives you limited amount of control over colors you are getting.

 quad.gameObject.GetComponent<Renderer>().material.color = Random.ColorHSV();

ColorHSV method has several overloads which gives you some control over color like using hueMin and hueMax.

Another option to have control over colors can be as @Szymon stated having a color array with plenty of colors and randoming an index between 0 and length of that array.

like image 146
Ali Kanat Avatar answered Mar 09 '23 05:03

Ali Kanat