0
\$\begingroup\$

Hi I have an empty object barHolder that I move between 10 and 98 on x-axis. It has 2 child images roundBar and bar. I am trying to change the color of roundBar and bar when the object is moving. On x=10 the the color will be red and on x=98 it will be green. Here is what I have done so far:

    public GameObject meterBarHolder;

    public GameObject barRoundHead;
    public GameObject bar;

    public Text meterSpeedText;
    int currentSpeed;

    Color maxColor = new Color(21, 193, 25, 255);
    Color minColor = new Color(229, 85, 85, 255);

    float totalSpeed;

    float speedPercentage;

    float pos;
    //--------------//

    private void Start()
    {
        totalSpeed = (float)PlayerPrefs.GetInt("speed");
    }

    // Update is called once per frame
    void Update()
    {
        currentSpeed = int.Parse(meterSpeedText.text);

        speedPercentage = (float)currentSpeed / totalSpeed;

        pos = 88 * speedPercentage;

        if(pos < 10)
        {
            meterBarHolder.gameObject.GetComponent<RectTransform>().localPosition = new Vector3(10f, 0f, 0f);
            changeColor(0);
        }
        else if(pos > 98)
        {
            meterBarHolder.gameObject.GetComponent<RectTransform>().localPosition = new Vector3(98f, 0f, 0f);
            changeColor(1);
        }
        else
        {
            meterBarHolder.gameObject.GetComponent<RectTransform>().localPosition = new Vector3(pos, 0f, 0f);
            changeColor(speedPercentage);
        }

    }

    void changeColor(float x)
    {
        bar.GetComponent<Image>().color = Color.Lerp(minColor, maxColor, x);
        barRoundHead.GetComponent<Image>().color = Color.Lerp(minColor, maxColor, x);
    }

The problem is that when ever I click play the color changes to white.

For reproducing the problem totalSpeed=120 and meterSpeedText changes between 0 and 120. The rest are calculated in the code.

Here is a gif to give an idea what I am trying to do:

enter image description here

\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

This is because you are using Color as if it was a Color32.

  • Color uses (float) values between 0 and 1
  • Color32 uses (byte) values between 0 and 255.

So a value greater then one is clamped to 1 for the shader, new Color(21, 193, 25, 255) is therefore to the shader the same color as new Color(1, 1, 1, 1) a.k.a. white.

So to fix this problem, you should either use Color32 instead of Color or change your input to float values ranging between 0 and 1.

Color32 can also be implicitly casted to a Color, so this would be the simplest solution:

Color maxColor = new Color32(21, 193, 25, 255);
Color minColor = new Color32(229, 85, 85, 255);
\$\endgroup\$
1
  • \$\begingroup\$ thanks man I use values from 0 to 1 and its working now. thanks a lot. \$\endgroup\$ Jul 23, 2019 at 14:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .