简体   繁体   中英

Array random color not generating

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)];
}

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)
}

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, eg

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)
};

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM