Colors from RGB are not correct Unity C#

11,976

You've misused the Color() constructor. Referring to the documentation, take note that parameters for the constructor should be float values in the range of [0,1]. If you don't want to calculate the appropriate values to supply, just divide them by 255:

new Color(0, 37/255f, 254/255f);

Alternatively, you may use the Color32() constructor, which takes int values in the range of [0,255]:

new Color32(0, 37, 254);

Color and Color32 can be implicitly converted to each other, so don't worry about casting issues. Hope this helps! Let me know if you have any questions.

Share:
11,976
Xephyr
Author by

Xephyr

Updated on June 13, 2022

Comments

  • Xephyr
    Xephyr almost 2 years

    So I have a 2D object that you can change the color of using buttons, and each button will change the sprite of the object. I have a sprite for red, orange, yellow, green, blue, purple.

    Now I have a particle system (A child of the object stated before) that I want to change the startColor property of to the same color as whatever the 2D object's sprite is. I'm using this code (Attached to the 2D object that you can change the sprite of):

            var sprite = gameObject.GetComponent<SpriteRenderer>().sprite;
            var startColor = gameObject.transform.GetChild(0).gameObject.GetComponent<ParticleSystem>().startColor;
    
            if (sprite == red) startColor = new Color(255, 29, 0);
            else if (sprite == orange) startColor = new Color(254, 32, 0);
            else if (sprite == yellow) startColor = new Color(254, 215, 0);
            else if (sprite == green) startColor = new Color(0, 254, 32);
            else if (sprite == blue) startColor = new Color(0, 37, 254);
            else if (sprite == purple) startColor = new Color(178, 0, 255);
    
            gameObject.transform.GetChild(0).gameObject.GetComponent<ParticleSystem>().startColor = startColor;
    

    All the new Colors() I'm trying to create from RGB. So I took the RGB value of the all color sprites and plugged them in. And when I executed the code, the color of the particles doesn't match the object's sprite color.

    NOTES: I'm running this on android, and the material for the particle system is plain white so it shouldn't tint the color.

    I put the RGB values from the color sprites in over five times. But it doesn't match the sprites! I don't know what's wrong... if you need me to attach the color sprite images, just ask.