0

In the current game I am creating I am attempting to have a dynamically changing health bar color corresponding to the current health of the enemy. When the health is at max the bar will be green (0, 255, 0), and when at low health the bar will be close to red (255, 0, 0). I coded the function to change from green to red depending on the current health of the enemy. When the enemy is at half health the color should be (125, 125, 0), however whenever I start the game the enemy begins at full health (green) and once the health is no longer at max, the bar is the same yellow until the enemy is dead. What part of my code makes it so that Unity cannot chance color simultaneously?

public void Start()
{
    health = maxHealth;
    healthBar.fillAmount = 1;
}

public void Update()
{
    canvas.transform.LookAt(tranformTarget);
    healthBar.fillAmount = health / maxHealth;

    greenColor = (int)(255 * healthBar.fillAmount);
    redColor = (int)(-255 * healthBar.fillAmount + 255);
    Color healthBarColor = new Color(redColor, greenColor, 0, 255);
    healthBar.color = healthBarColor;
    Debug.Log(greenColor);
    Debug.Log(redColor);
}
Ruzihm
  • 19,749
  • 5
  • 36
  • 48
cory
  • 11
  • 1
  • 4

1 Answers1

1

Your code will not work as you desire, because Unity's color works with normals. https://docs.unity3d.com/ScriptReference/Color-ctor.html

So you will need a float ranging from 0-1.

Try this.

canvas.transform.LookAt(tranformTarget);
healthBar.fillAmount = health / maxHealth;

var green = healthBar.fillAmount;
var red = -1 * healthBar.fillAmount + 1;
Color healthBarColor = new Color(red, green, 0f, 1f);
healthBar.color = healthBarColor;

Note that you can also ommit the alpha parameter if you simply want alpha to be 1.

Immorality
  • 2,164
  • 2
  • 12
  • 24