Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unity Variable gets Infinity

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++; }

}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading