I’m testing something in the editor so that I can detect if my iOS app is running on a 4:3 or 3:2 ratio screen (i.e. iPad or not).
Run the game in Unity with the following line and it returns 0 (The game is portrait, printing Screen.width returns 768, printing Screen.height returns 1024):
print (Screen.width / Screen.height);
Switch that around to the following and it returns 1:
print (Screen.height / Screen.width);
It seems to be giving an integer when I want a float, so I tried the following to make sure I got a float, but it didn’t help:
var ratio : float;
ratio = Screen.width / Screen.height;
print (ratio);
I’ve got results with decimal places with a Print before, so I don’t understand. Can anyone help?
In C#
float ratio = screen.width/(float)screen.height; //cast denominator to float to ensure correct division
In Javascript
var ratio:float = screen.width/float(screen.height):
or
var ratio:float = screen.width/(screen.height as float); //does “as” actually work in Javascript?
or
var sh:float = screen.height;
var sw:float =screen.width;
var ratio:float = sw/sh;
etc.
Thanks Antitheory, I got that to work. Does this mean a float var produces an integer result if it divides integers? Or is it a different problem that is being solved?
This should work.
var ratio : float;
var resultStr : String = "";
function Start()
{
Debug.Log("the type of value is " + typeof(Screen.width)); // This gives --> System.Int32
ratio = parseFloat(Screen.width) / parseFloat(Screen.height);
resultStr = "The result is " + ratio.ToString();
}
function OnGUI()
{
GUI.Label(new Rect(10,10,200,40), resultStr);
}
Screen.width and Screen.height are ints. It doesn’t make sense that they would be floats (how do you have 0.5 pixels exactly?)
When dividing by an integer you will always have an integer result, no matter what the return type is
(someFloat/someInt)
always will come out as int, regardless of where that occurs, even in a method call.
Mathf.CeilToInt(3/4);
will come out as 1, as it should… but
Mathf.CeilToInt(5/4);
will also come out as 1, because 5/4 = 1 whereas 5/4f = 1.25f
There are some rare instances where you want to divide by an integer… like in an array index for example
for (int i=0;i<100;i+2)
someArray[i / 2] = i;
Is ok because you know that ‘i’ will always divide by two anyways
Thank you ahmetDP, I can use parseFloat(Screen.width) / parseFloat(Screen.height) within an if statement so that I do not have to create any variables.
parseFloat casts Screen.width to a String, and parses the String to a float. That makes no sense at all. You know Screen.width and Screen.height are ints. Just cast it directly
float(Screen.width)