- Home /
float = int / int float value always 0
So i'm having a kind of confusing issue when I cast a float and then try and populate it with 2 integers divided into one another. The exact case here is health bars. I'm simply trying to get a % float value out of my integer based health values.
void Start () {
life = true;
maxHealth = Health;
Debug.Log("maxHealth" + maxHealth.ToString());
}
public void takeDamage (int dmg) {
Debug.Log("dmg" + dmg.ToString());
Health -= dmg;
updateBar();
}
void updateBar () {
float newHealth = Health / maxHealth;
Debug.Log("newValue" + newHealth.ToString());
healthBar.sliderValue = newHealth;
}
When an enemy takes damage I call the takeDamage method. Here's a sample of the debug output I am seeing in the log from my prints
maxHealth100, dmg12, newValue0
Am I not able to get a float out of 2 int's like this? Am I better off just casting my health values as floats?
Answer by OperationDogBird · Aug 14, 2012 at 07:55 AM
With int operations the return will always be an int. You will need to make one of them a float in order to get a float return.
float mhFloat = maxHealth+0.1;
mhFloat-=0.1;
float newHealth = Health / mhFloat;
Not sure if thatll work, but it should.
EXCELLENT!!!
I was actually able to just cast one of the values as a float in the division!
float newHealth = Health / (float)maxHealth;
Thanks so much!
Oh yeah, forgot about casting in C#. That is much more elegant than my hack version LOL
Np
Your answer
Follow this Question
Related Questions
Have a problems with a values 1 Answer
Can I create a list with an int/float and a string? C# 2 Answers
Convert a char to int / float 2 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers