Trigger script on android auto-rotation?

I’ve got a game set to auto-rotate in the unity android player preferences. However, when it rotates from landscape into portrait view part of the game becomes hidden off the sides of the screen. I can easily fix this by adjusting some settings on the camera, but how do I detect that the screen has rotated so I can trigger a script to make the changes?

Any help is appreciated!

You can make an infinite coroutine and check there current orientation of device and sent notification if it’s changed.

Edit: I found that the problem was that I wasn’t uninstalling the app between tests and somehow this was causing it to run former code even though nothing about this was being saved in player prefs.


In an attempt to put this idea into practice I’ve tried several things with no success.

First, I get the following errors when trying to use what I think is the correct format to do this:

if (Screen.orientation == ScreenOrientation.Landscape) {
//'Landscape' is not a member of 'ScreenOrientation'.
if (Screen.orientation == ScreenOrientation.LandscapeLeft) {
//'LandscapeLeft' is not a member of 'ScreenOrientation'.

Since that throws errors at me I tried the following two options, which don’t create errors but also don’t seem to work. In the following two examples landscape and portrait are booleans set to false at start and when the SwitchToLandscape function runs landscape is set to true and portrait is set to false, and vice versa for the SwitchToPortrait function so that the functions only run when the switch is made.

Just fyi, autorotate doesn’t seem to work when using unity remote so in order to test each change I have to build the game and install it on my android. Debugging on my android shows that the functions are not running.

function Update () {

	if (Screen.orientation == 1  !landscape) {								//If orientation is landscape and the SwitchToLandscape function has not run
		SwitchToLandscape ();													//Run the SwitchToLandscape function
	}

	if (Screen.orientation == 0  !portrait) {									//If orientation is portrait and the SwitchToPortrait function has not run
		SwitchToPortrait ();													//Run the SwitchToPortrait function
	}

}
function Update () {

	if (Screen.height < Screen.width  !landscape) {							//If orientation is landscape and the SwitchToLandscape function has not run
		SwitchToLandscape ();													//Run the SwitchToLandscape function
	}

	if (Screen.width < Screen.height  !portrait) {							//If orientation is portrait and the SwitchToPortrait function has not run
		SwitchToPortrait ();													//Run the SwitchToPortrait function
	}

}

Any ideas where I’m going wrong here?