- Home /
How can I detect device orientation change in a fast and reliable way?
I am using OnRectTransformDimensionsChange to detect between portrait and landscape. Basically I have something like this:
if (Screen.orientation == ScreenOrientation.Portrait || Screen.orientation == ScreenOrientation.PortraitUpsideDown) {
myAnimator.SetBool("isPortrait", true)
} else {
myAnimator.SetBool("isPortrait", false);
}
However this code sometimes fails. If I do a GetBool on 'isPortrait', sometimes when it's portrait the variable report that it's not and vice-versa. To fix this, I did:
void Update() {
if (Screen.orientation == ScreenOrientation.Portrait || Screen.orientation == ScreenOrientation.PortraitUpsideDown) {
if (myAnimator.GetBool("isPortrait") == false) {
myAnimator.SetBool("isPortrait", true);
}
} else {
if (MenuRetratilAnimator.GetBool("isPortrait") == true) {
myAnimator.SetBool("isPortrait", false);
}
}
}
The code above works fine, no issues. But it lags my experience on android. How can I change the user interface in a fast and reliable way depending on the screen orientation? Thank you.
Answer by nikescar · Jan 12, 2019 at 10:09 PM
Have you looked into DeviceOrientation?
Interesting, the code doesn't seem to fail now. I will have to test some more just to be sure...all I did was change ScreenOrientation to DeviceOrientation. Seems like they do basically the same thing so I don't know why ScreenOrientation is unreliable.
I think if your app is set to only allow certain rotations then screenOrientation will not change. Perhaps that is your issue?
Answer by badadam · Jan 14, 2019 at 01:36 PM
void Update () {
if (Input.deviceOrientation==DeviceOrientation.Portrait||Input.deviceOrientation==DeviceOrientation.PortraitUpsideDown)
{
//codes for portrait
}
else
{
//codes for Landspace;
}
}
The update method is more intensive and makes my phone burn hot. This is not an option. The problem is already solved apparently as per my comment to @nikescar .
Nikescar's comment uses an update loop as well.
I don't think an update loop with a couple if statements is going to make your phone run hot, but it would be nice if there were an option that was an event listener instead of an update loop.