- Home /
Unity not dividing correctly C# camera pixel width & height
For some reason Unity isn't dividing something correctly. Here is the example:
Debug.Log(Camera.main.pixelWidth);
Debug.Log(Camera.main.pixelHeight);
Debug.Log(Camera.main.pixelWidth / Camera.main.pixelHeight);
The first debug is returning a value of 625. The second debug is returning a value of 352. But the last debug for some reason is returning a value of 1. Why is it returning 1? It doesn't seem to be a rounding problem because if Unity were rounding 625/352 it would be debugging a 2 (because 625/352 is 1.78 which is closer to a 2 than a 1). Is there a way to make unity divide this correctly in C#?
Answer by MaxGuernseyIII · Jul 16, 2018 at 09:42 PM
It is dividing correctly. Integers are divided using integer arithmetic. You just have to dig way back to grade-school and remember the way you were taught before you understood things like decimals...
Before eleven divided by four was 2.75, it was two with a remainder of three.
When dividing integers, division gives the integer part of the result and modulus gives you the remainder.
If you want something that approximates real number division, like we are conditioned to think about later in life, you want a floating point number.
You can get that by multiplying the numerator or the denominator by 1f or 1d.
Or you can cast one of the operands to a floating-point value:
Debug.Log(Camera.main.pixelWidth / (float)Camera.main.pixelHeight);
I bet there's more than a dozen ways to do it.
float numerator = ...; var numerator = (float)...; Convert.ToFloat(...) (float)... / ...; (1f * ...)
Then all the double equivalents.
$$anonymous$$aybe there aren't a dozen truly-distinct and simple ways to do it but there are plenty of paths to the same destination.