Zak Woolley
Zak Woolley

Reputation: 179

Unity: Progress Bar rounding to nearest whole number

I'm trying to make a timer progress bar. I'm using a slider UI element for this and changing the value of it through code. However, it seems that the value is rounding up to the nearest whole number even though it's a float and not an int. I say this because for the first half of the time, the bar is full, and for the second half is empty. Can anyone help? Thanks.

public int totalTime = 4;
int time = 4;

public Slider clock;

// Use this for initialization
void Start () {

    time = totalTime;

    clock.value = CalculateTime();

    StartCoroutine(Timer());
}

IEnumerator Timer()
{

    yield return new WaitForSeconds(1);
    time = time - 1;
    clock.value = CalculateTime();
    if (time != 0)
    {
        StartCoroutine(Timer());

    }
    else
    {
        Fin();

    }
}

float CalculateTime()
{
    return time / totalTime;
}

Upvotes: 0

Views: 333

Answers (1)

Programmer
Programmer

Reputation: 125325

time is int and totalTime is int. If you divide both, you get int as a result not float.'' The rest of the result will be thrown away.

To get actually get float you have to cast that int to float during the division.

At-least, one of the two numbers you are diving must be float in order to get float.

This:

float CalculateTime()
{
    return (float)time / totalTime;
}

This:

float CalculateTime()
{
    return time / (float)totalTime;
}

Or This:

float CalculateTime()
{
    return (float)time / (float)totalTime;
}

should work.

Upvotes: 3

Related Questions