Double vs Float
I am making a health bar in my game and I think that I need to used a float. When I try to used a float, I need it to be a fraction or a decimal, but I don't believe that you can make fractions and When I try to use a double instead of a float, I get and error. Is there a way to make a double into a float or is float not what I need to used. Here is my code:
Public GameObject Content;
double HealthPercentage;
void Update () {
if (Input.GetKeyDown(KeyCode.K)) {
HealthPercentage = HealthPercentage – 0.1;
//If K is pressed, hurt character
}
}
void HealthBar () {
Content.FillAmount = HealthPercentage;
}
In My game, I am trying to make a UI image and it has a Filled turned on so I can adjust the amount of Health that shows in the bar. In My code, I am currently using a double, but I believe that I need a float where the HealthPercentage variable is. How can I make it so that a float can be a fraction of 1 and so that I can change it later in my script?
Thanks I am using C#
What does putting and f after the double do to make if a float? What does adding f mean?
Answer by v01pe_ · May 19, 2016 at 08:21 AM
Hi, for storing health using a float
is definitely precise enough - it actually is for most applications.
First, if that's the whole code for your component, you should instantiate the variable at some point - either in the Start()
method or when declaring it:
float HealthPercentage = 1.0f;
The f literal is used to make a floating-point value of float precision. An other way to convert a double to a float would be casting:
double doubleValue = 0.1;
float floatValue = (float)doubleValue;
In your case, changing the variable later would be done like this:
HealthPercentage = HealthPercentage – 0.1f;
or in shorter form:
HealthPercentage -= 0.1f;
I suggest looking at some basic coding tutorials this will help you a lot in the long run. Hope this helps!