- Home /
Choose random color from a gradient for sprite renderer?
Hello I have a beautiful gradient colors I made & applied public Gradient gradient
to my script for a gameobject sprite renderer to choose a random color from the gradient made. Is there a way I can do this?
Answer by Namey5 · Mar 29, 2020 at 07:21 AM
You can get a random colour from a gradient via the following;
Color randColor = gradient.Evaluate (Random.Range (0f, 1f));
Hello, I applied the following code in my script void changeColor() { Color randColor = gradient.Evaluate(Random.Range(0, 1)); GetComponent().color = randColor; }
but for some reason only stuck on the first color of the gradient
'GetComponent' doesn't really make sense in this context - you need to specify what kind of component you wish to get;
GetComponent<SpriteRenderer>().color = randColor;
Also, pay close attention to the fact that I wrote 'Random.Range (0f, 1f)' not 'Random.Range (0, 1)', as these are both two entirely different functions - the second one will only ever return 0.
Thank you for your help. I had no idea about the f's made a major difference.
Your answer
