Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to detect the "natural" orientation of an Android device in Unity3D. Also can use to detect tablet and phone.
using UnityEngine;
using System.Collections;
public class NaturalOrientation : MonoBehaviour {
public static int ORIENTATION_UNDEFINED = 0x00000000;
public static int ORIENTATION_PORTRAIT = 0x00000001;
public static int ORIENTATION_LANDSCAPE = 0x00000002;
public static int ROTATION_0 = 0x00000000;
public static int ROTATION_180 = 0x00000002;
public static int ROTATION_270 = 0x00000003;
public static int ROTATION_90 = 0x00000001;
public static int PORTRAIT = 0;
public static int PORTRAIT_UPSIDEDOWN = 1;
public static int LANDSCAPE = 2;
public static int LANDSCAPE_LEFT = 3;
#if UNITY_ANDROID
AndroidJavaObject mConfig;
AndroidJavaObject mWindowManager;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
//adapted from http://stackoverflow.com/questions/4553650/how-to-check-device-natural-default-orientation-on-android-i-e-get-landscape/4555528#4555528
public int GetDeviceDefaultOrientation()
{
if ((mWindowManager == null) || (mConfig == null))
{
using (AndroidJavaObject activity = new AndroidJavaClass("com.unity3d.player.UnityPlayer").
GetStatic<AndroidJavaObject>("currentActivity"))
{
mWindowManager = activity.Call<AndroidJavaObject>("getSystemService","window");
mConfig = activity.Call<AndroidJavaObject>("getResources").Call<AndroidJavaObject>("getConfiguration");
}
}
int lRotation = mWindowManager.Call<AndroidJavaObject>("getDefaultDisplay").Call<int>("getRotation");
int dOrientation = mConfig.Get<int>("orientation");
if( (((lRotation == ROTATION_0) || (lRotation == ROTATION_180)) && (dOrientation == ORIENTATION_LANDSCAPE)) ||
(((lRotation == ROTATION_90) || (lRotation == ROTATION_270)) && (dOrientation == ORIENTATION_PORTRAIT)))
{
return(LANDSCAPE); //TABLET
}
return (PORTRAIT); //PHONE
}
#endif
}
@sampalmer

This comment has been minimized.

Copy link

sampalmer commented Jan 22, 2015

I've seen getRotation() and orientation go out of sync sometimes, so this isn't a perfect solution.

@LucasCosson

This comment has been minimized.

Copy link

LucasCosson commented Oct 19, 2015

Unfortunately, it seems to apply only in if the orientation of the device is not set manually.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.