armnotstrong
armnotstrong

Reputation: 9065

Why change color to yellow not working with spriteRenderer programically in unity?

I have a flower of which the petals are individually from the stalk:

enter image description here

I have no problem to change the petals to green or black with following script:

private void Start()
{
    flower = transform.GetChild(transform.childCount - 1).gameObject;
    if (Random.Range(0, 1.0f) < 0.5f)
    {
        for (int i = 0; i < flower.transform.childCount; i++)
        {
            flower.transform.GetChild(i).gameObject.GetComponent<SpriteRenderer>().color = Color.green;// Color.yellow;
        }
    }
}

enter image description here

But what is weird is that the color will not change to yellow with this:

flower.transform.GetChild(i).gameObject.GetComponent<SpriteRenderer>().color = Color.yellow;

Note that, the Random.range() is not the problem. It just couldn't change to yellow/ or white, but colors such as black, green will be ok.

And if you may forgive me to ask another question, is the color representation of rgba from 0-1 is that of in Photoshop representation 0-255 divided by 255? Such that a color RGBA(255,255,1,255) will be Color(255/255.0, 255/255.0, 1/255.0, 255/255.0) which will come to Color(1.0f,1.0f,0.00001f, 1.0f) in Unity?

FYI, the attribute of the petals' spriteRenderer is as following, and I use the Sprite-Default material: enter image description here

EDIT:

Add the raw sprite sheet as required by comment:

enter image description here

Upvotes: 2

Views: 3926

Answers (1)

Danny Herbert
Danny Herbert

Reputation: 2031

You need to make the petals of the flower sprite white. (i.e change them in your sprite editing software, NOT in Unity). This will allow you to change the color of the sprite in the editor.

To check this, try just changing the color of the Sprite Renderer component to yellow in the inspector. It should still be red. Also check if the Sprite Renderer component's color field is yellow at run time. This will allow you to be certain that the code is working.

The problem is not your code; the problem is how the sprite's shader works. The sprite-default shader works by multiplying the color field that you are changing by the actual RGB value of the sprite. If the value of one of the RGB fields is 0 in the sprite's texture then multiplying it by some value will mean that it is still 0. I think that is what is happening for you.

You can see this happening by importing a pure red sprite and then trying to change the color of it in the inspector. It will just turn black.

If you are curious, you can download the source code for Unity's built in shaders Here.

Upvotes: 6

Related Questions