- Home /
Two floats == Percentage
I feel like this should be a very easy task, the more I try new things and more research I do, the more confused I get.
The code below is from one script, the other script is essentially what holds my TextMesh(s). The way it's set up, CurrentMeter goes from 0% to 100%. Once it reaches 100% it jumps directly back to 0%.
What i'm trying to do is: I want to flip the percentages so it starts at 100%, goes down to 0%. When at 0% I want it to gradually climb back up to 100% at the same pace as the Time.deltaTime.
public float meterTime = 0.0F;
public float meterMax = 5.0F;
void CheckMeter()
{
meterTime += Time.deltaTime;
if(meterTime >= meterMax)
{
//Activate something by boolean
meterTime = 0;
}
}
void UpdateMeter()
{
CurrentMeter = (meterTime / meterMax) * 50;
ModifyMeter (CurrentMeter) //<---- linked to a HUD Script
}
This is my very first post on here, so if my format is incorrect or sloppy i'm sorry. Id rather someone point out the issue and let me know so I won't do it again.
Answer by Mmmpies · Dec 02, 2014 at 10:15 PM
If I've got it right (and it's late where I am!) then you're re-setting meterTime to 0.
Really meterTime is just a float so when you get to 100% meterMax (or just above) you need to change meterTime += Time.deltaTime to meterTime -= Time.deltaTime Until it gets to 0 again.
set a bool for positive or negative bool PosNeg and if true do meterTime += if false do meterTime -=
You'll also need a meterLow to handle when it reaches 0 (or just use 0)
This worked great, another simple thing I felt like I should have thought of. I greatly appreciate the input. I used another bool to pause and restart the meterTime in the opposite direction.
Answer by SquigglyFrog · Dec 02, 2014 at 10:43 PM
Another way is to just have a INT specifying which direction its going..
int direction = 1;
meterTime += Time.deltaTime * direction;
When you want to change direction, just do
direction *= -1;
Answer by Kiwasi · Dec 02, 2014 at 10:48 PM
Some simple mathematical tricks that will help.
% operator. This returns the remainder after division.
1 - . This can be used to flip a value.
No sure is % is appropriate for your code. But you can implement the subtraction simply by
CurrentMeter = (1 - meterTime / meterMax) * 50; // Why 50? Percent is 100
I feel a bit foolish, I don't know why I didn't think of using a 1 -. Thank you for that tip. The reason it is set to 50 is because when multiplied by 50 it goes from 0 - 100. If I set it to 100 it runs from 0 - 100. Doesn't make any sense to me.
Your answer
![](https://koobas.hobune.stream/wayback/20220613173025im_/https://answers.unity.com/themes/thub/images/avi.jpg)