1
\$\begingroup\$

I need to change the color of my SpriteRenderer, and so I looked up how to do it and come up with this code:

spaceOne.GetComponent<SpriteRenderer>().color = new Color(166, 33, 33);

(In case you are wondering, yes I checked that 'spaceOne' is correctly linked to a GameObject.)

This should change the color, but it doesn't. As I was writing this, I found that replacing new Color(166, 33, 33); with Color.red; actually does change it to red.

So now I am wondering, why does the new Color(166, 33, 33); code not work, and how can I fix it?

P.S. I made sure that it wasn't something simple, like it being RGBA rather than RGB, but no, it still doesn't work with new Color(166, 33, 33, 255);.

\$\endgroup\$
2
\$\begingroup\$

The color component of a SpriteRenderer defaults to white. The Color type is a four-component, RGBA, floating point representation of a color. The range of each component of that type is 0.0 to 1.0.

In your code, you're passing integers for each component, and all of them are greater than one. The documentation doesn't specify what happens if you do this, but there's a good chance it just clamps them to 1. So you're essentially just setting the color to white (which it already was), and thus seeing no results.

Try dividing all your components by 255.0f:

spaceOne.GetComponent<SpriteRenderer>().color = new Color(
  166.0f / 255.0f,
  33.0f / 255.0f,
  33.0f / 255.0f
);
| improve this answer | |
\$\endgroup\$
-3
\$\begingroup\$

I experienced the same Problem, but found an other solution:

spaceOne.GetComponent<SpriteRenderer>().color = new Color( 166.0f, 33.0f, 33.0f, 1 );

i forget the alpha chanel

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ This doesn't appear to answer OP's original question, since they explicitly mention that they tried providing an alpha value too. \$\endgroup\$ – DMGregory Mar 28 '19 at 0:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.