0
\$\begingroup\$

Currently working on an overhead display of the health bar and ran into this problem and I cannot seem to figure out why its not working correctly. When the player has less than entity.health.max the scale is set to 0 instead of the calculated percent.

Code:

private void SetHealth(int amount)
{
  currentHealth = amount;
  float displayedHealth = currentHealth / entity.health.max;
  healthBar.transform.localScale = new Vector3(displayedHealth, 1, 1);
}

I also tried the following with the same results

float displayedHealth = Mathf.Lerp(0, 1, currentHealth / entity.health.max);
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

The solution was to cast both int as float

float displayedHealth = (float)currentHealth / (float)entity.health.max;

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Casting just one term should be sufficient. int / int division in C# truncates, but float / int and int / float implicitly casts the mismatched integer into a float for you. \$\endgroup\$
    – DMGregory
    Commented Feb 26, 2022 at 15:01

You must log in to answer this question.

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