1

I'm facing a problem where when I declare array of random colors. It shows random colors in a particle system on game start, but every time the game starts it shows white. I don't know why it happens, I didn't set white in my array.

public class A : MonoBehaviour 
{       
   Color[] colors = {
   new Color (170, 7, 107),
   new Color (58, 96, 115),
   new Color(81, 99, 149),
   new Color(71, 118, 231)
};

void start()
{
   GetComponent<ParticleSystem>().startColor =  colors[Random.Range(0, colors.Length)];
}
Tom
  • 2,372
  • 4
  • 25
  • 45

3 Answers3

3

In Unity, a color's ARGB components range between 0.0 to 1.0. So anything >1 will be considered 1 and so all the colors are white naturally.

To convert the colors, divide each component by 255. You can either do this yourself or leave it to the code itself. Also, don't forget to cast as float. Credit to @Masih Akbari for reminding me about this.

So, it should be :

Color[] colors = {
    new Color (170f/255, 7f/255, 107f/255),
    new Color (58f/255, 96f/255, 115f/255),
    new Color(81f/255, 99f/255, 149f/255),
    new Color(71f/255, 118f/255, 231f/255)
}
Fᴀʀʜᴀɴ Aɴᴀᴍ
  • 6,131
  • 5
  • 31
  • 52
1

The reason for this is that colours are normalised in Unity. You have to divide each float you've set by 255 to get the actual value, e.g.

Color[] colors = {

    new Color (170/255, 7/255, 107/255),
    new Color (58/255, 96/255, 115/255),
    new Color(81/255, 99/255, 149/255),
    new Color(71/255, 118/255, 231/255)
};
Philip Rowlands
  • 283
  • 5
  • 17
  • 1
    `170/255` is... `0` (integer division), so you'll have `new Color(0, 0, 0)` in fact (`Black`) – Dmitry Bychenko Dec 01 '15 at 09:11
  • @DmitryBychenko How to fix that what does mean 255 is magic value –  Dec 01 '15 at 09:12
  • @Tim Allen: `170f/255` or `170/255f` or `(float) (170.0/255.0)` etc. – Dmitry Bychenko Dec 01 '15 at 09:13
  • 1
    @TimAllen [Magic Number](http://stackoverflow.com/questions/47882/what-is-a-magic-number-and-why-is-it-bad) is nothing but a number used directly instead of first declaring it as a constant. It will **not** make the code malfunction but it is a better practice not to use magic numbers, – Fᴀʀʜᴀɴ Aɴᴀᴍ Dec 01 '15 at 10:01
0

Your Color values must be between 0 to 1. everything after 1 is considered white.

Don't forget to cast your number as a float

dev-masih
  • 4,188
  • 3
  • 33
  • 55