Home > Software engineering >  Unity Variable gets Infinity
Unity Variable gets Infinity

Time:12-08

I just wanted to use simple math in my script, but as soon as I start it, "Percent Red" gets infinity. Ive researched and I found out that it can be caused by a DivisionByZero, but I don't know what I did wrong, I have tried everything I could.

void Start(){
    RedClick = 10;
    BlueClick = 10;
}

void Update()
{
    AllClicks = RedClick   BlueClick;
    Percent = AllClicks / 100;
    PercentRed = RedClick / Percent;
    RedFill.fillAmount = PercentRed;
}

public void RedButton(){ RedClick  ; }
public void BlueButton(){ BlueClick  ; }

}

CodePudding user response:

I can just guess but from your results and ho you use them I'd assume that all of these RedClick, BlueClick, Percent, AllClicks are of type int.

So, what you get is an Integer division! For int values the / is without decimals!

=> as long as AllClicks < 100 you get

Percent = 0;

and then

PercentRed = RedClick / 0;

division by 0 in general is not too good ;)


simple fix: Use float division!

So your field Percent should be a float

float Percent;

and then use the post-fix f literal to use a float instead of an integer decimal (default in c# without specifier) for your value 100

Percent = AllClicks / 100f;
  • Related