简体   繁体   中英

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?

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");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM