Reputation: 39
I tried to add some variation to the colour of each sprite using the following code:
spriterenderer.color = colour+ new Color32(Convert.ToByte(rnd.Next(-10,10)), Convert.ToByte(rnd.Next(-10, 10)), Convert.ToByte(rnd.Next(-10, 10)),255);
This did not work, what way should I do this?
Upvotes: 0
Views: 155
Reputation: 90580
Color32
always has components that are clamped to 0 - 255
. You will never get negative values anyway.
Additionally you are using Convert.ToByte
. A byte
itself already can not be negative either and for negative values you will get a
System.OverflowException: Value was either too large or too small for an unsigned byte.
You should rather go component wise and do something like e.g.
// Implicit conversion Color -> Color32
Color32 temp = colour;
// This makes sure the value never goes under 0 or beyond 255
temp.r = (byte) Mathf.Clamp(temp.r + UnityEngine.Random.Range(-10, 11), byte.MinValue, byte.MaxValue);
temp.g = (byte) Mathf.Clamp(temp.g + UnityEngine.Random.Range(-10, 11), byte.MinValue, byte.MaxValue);
temp.b = (byte) Mathf.Clamp(temp.b + UnityEngine.Random.Range(-10, 11), byte.MinValue, byte.MaxValue);
spriterenderer.color = temp;
Upvotes: 1