How to generate a random color?
I tried to generate a random color like this:
Color background = new Color(
(float)Random.Range(0, 255),
(float)Random.Range(0, 255),
(float)Random.Range(0, 255)
);
But I always get white as result.
What am I doing wrong?
Answer by Hellium · Oct 28, 2017 at 09:10 PM
As suggested by Dragate, the Color
struct needs values between 0 and 1, as indicated in the documentation
Representation of RGBA colors.
This structure is used throughout Unity to pass colors around. Each color component is a floating point value with a range from 0 to 1.
In order to use values between 0 and 255, you need the Color32 class :
Color32 background = new Color32(
Random.Range(0, 255),
Random.Range(0, 255),
Random.Range(0, 255),
255
);
// Color version
Color background = new Color(
Random.Range(0f, 1f),
Random.Range(0f, 1f),
Random.Range(0f, 1f)
);
Answer by Dragate · Oct 28, 2017 at 06:20 PM
Color background = new Color(
Random.Range(0f, 1f),
Random.Range(0f, 1f),
Random.Range(0f, 1f)
);
Answer by AmmarSalim · Oct 22, 2020 at 08:55 AM
This is the simplest: { // Pick a random, saturated and not-too-dark color GetComponent().material.color = Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f); }
Sweet AmmarSalim..i just needed to specify the renderer when attached to my gameObject. But yeh your code worked. Big up ! Thanks
obj.GetComponent().material.color = Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f);
Answer by krokots · Oct 28, 2017 at 05:55 PM
Maybe try this:
string seed = Time.time.ToString ();
System.Random random = new System.Random (seed.GetHashCode ());
Color background = new Color(
(float)random.Next(0, 255),
(float)random.Next(0, 255),
(float)random.Next(0, 255)
);
Your answer
Follow this Question
Related Questions
Color Randomize when object spawn help 0 Answers
Different random number - Same script - Different cloned object 0 Answers
continuously spawning and causes spawned objects to overlap 0 Answers
Need help with specifics in Random.Range 1 Answer
Hi guys, I need help with C# Scripting using Raycast. 1 Answer