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: