Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get the orientation of the device with unity3d

Im making my first 2d game with unity and im trying to do a main menu.

void OnGUI(){
    GUI.DrawTexture (new Rect (0, 0, Screen.width, Screen.height), MyTexture);
    if (Screen.orientation == ScreenOrientation.Landscape) {
        GUI.Button(new Rect(Screen.width * .25f, Screen.height * .5f, Screen.width * .5f, 50f), "Start Game"); 
    } else {
        GUI.Button(new Rect(0, Screen.height * .4f, Screen.width, Screen.height * .1f), "Register"); 
    }
}

I want to write out start game button if the orientation of the device is in landscape and the register if it is in portrait. Now it writes out Register button even though i play my game in landscape mode. What is wrong?

like image 494
Daniel Gustafsson Avatar asked Sep 07 '25 15:09

Daniel Gustafsson


1 Answers

Screen.orientation is used to tell the application how to handle device orientation events. It is probably actually set to ScreenOrientation.AutoOrientation. Assigning to this property dictates to the application what orientation to switch to, but reading from it does not necessarily inform you what orientation the device is currently in.

Using the device orientation

You can use Input.deviceOrientation to get the device's current orientation. Note that the DeviceOrientation enum is fairly specific, so your conditionals might have to check for things like DeviceOrientation.FaceUp. But this property should give you what you're looking for. You'll just have to test the different orientations and see what makes sense for you.

Example:

if(Input.deviceOrientation == DeviceOrientation.LandscapeLeft || 
     Input.deviceOrientation == DeviceOrientation.LandscapeRight) {
    Debug.log("we landscape now.");
} else if(Input.deviceOrientation == DeviceOrientation.Portrait) {
    Debug.log("we portrait now");
}
//etc

Using the display resolution

You can get the display resolution using the Screen class. A simple check for landscape is:

if(Screen.width > Screen.height) {
    Debug.Log("this is probably landscape");
} else {
    Debug.Log("this is portrait most likely");
}
like image 167
Zach Thacker Avatar answered Sep 10 '25 08:09

Zach Thacker