Random colour in Unity

I want to have a random colour for my background, and then that same colour just darker for my camera background. How would I do this?

using UnityEngine;

public class BlockSpawner : MonoBehaviour {

    public Transform[] spawnPoints;
    public GameObject blockPrefab;
    private float timeToSpawn = 2f;
    public float timeBetweenWaves = 1f;
    public GameObject background;
    public Camera camera;

    void Update () {

        if (Time.time >= timeToSpawn) {
            SpawnBlocks ();
            timeToSpawn = Time.time + timeBetweenWaves;
        }

    }

    void SpawnBlocks() {
        int randomIndex = Random.Range (0, spawnPoints.Length);
        SpriteRenderer renderer = background.GetComponent<SpriteRenderer>();

        for (int i = 0; i < spawnPoints.Length; i++) {
            if (randomIndex != i) {
                Instantiate (blockPrefab, spawnPoints [i].position, Quaternion.identity);
            }

            if (i == 1) {
                renderer.material.color = //Random Colour;
                camera.backgroundColor = //The same random colour but darker;
            }
        }
    }

}

First off you are going to want to set your color as a variable instead of just assigning it, and then you are going to want to use Random.Range to get your random number, so something like this :

public Color color;

color = new Color(Random.Range(0F,1F), Random.Range(0, 1F), Random.Range(0, 1F));

The colors will sometimes come out really dark so you might want to set a minimum number it can get “Random.Range(.3F,1F)” and I never knew Colors numbers were 0-1 I always thought it was 0-255 but it will take alot of playing around with, I found if I set it to (.3F, 3F) you get brighter colors but then if you try and edit it in inspector it throws a error and resets it to a valid number. or if that is not what you wanted, you could just make a list of custom numbers set by yourself and then just use Random.Range to pick the number from the list. as for making them darker you could create another variable for it(if you are going to use the color more then once) or just do

new Color(color.r - 10, color.g - 10, color.b - 10);

And if the colors red is 9 and you try and - 10 it is obviously going to throw you a error so you are going to want to check that, and -10 is hardly anything just play with the numbers and as for setting the colors :

        obj.GetComponent<Renderer>().material.color = color; //Set it to a object

        cam.backgroundColor = color; //Set it to Camera background

Hope this helps

1 Like

My 2cents:

GetComponent().material.color = UnityEngine.Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f);

3 Likes

Thanks this really helped!