fillAmount problem

Hello everyone,

I have a problem to understand something.
I have 2 variables :
public int maxhealth;
public int health;

I want to display an healthbar, i have this line :
hpImage.fillAmount = health / maxhealth;
I can’t understand why hpImage.fillAmount can return only 1 or 0

For exemple health = 99 and maxhealth = 100 → hpImage.fillAmount = 0

But if i do this (set variables → float), it works correctly:
hpImage.fillAmount = (float)health / (float)maxhealth;

For exemple health = 99 and maxhealth = 100 → hpImage.fillAmount = 0.99

So my healthbar works perfectly but i can’t undertstand why if health and maxhealth are int i have an issue.

Can you help me?

In C# (and other statically typed languages like C++ and Java), the types of the operands for addition/division/etc determine how the operation is carried out. In this case, since health and maxhealth (by the way, you might want to name this maxHealth for convention’s sake) are integers, you’re going to be performing integer division and get an integer. Then you’re going to lose the fractional component of the quotient. Using integer operands will cause you to perform an integer operation. If either one of the operands is of a floating-point type, you’ll get floating-point division. It’s basically a rule to cast either one of the operands for a binary operator to a floating-point type if you want to get a floating-point result.

3 Likes