Android screen orientation: why am I getting wrong screen size values?

Hi there,

I’ve run into a problem that I can’t seem to figure out. My goal is to execute some code after the screen orientation has changed; for example when the device has been rotated from landscape to portrait mode. The actual function call works fine, but when I try to receive the dimensions of the screen, while they were perfectly fine just before the function was executed! The problem occurs in an otherwise empty project and scene, on both a Samsung Galaxy Tab 2 and a Samsung Galaxy S2.

	private ScreenOrientation screenOrientation;
	private float screenWidth;
	private float screenHeight;
	private float wrongWidth;
	private float wrongHeight;
	
	public void Update()
	{
		//These values are right
		this.screenWidth = Screen.width;
		this.screenHeight = Screen.height;
		
		if (this.screenOrientation != Screen.orientation)
		{
			this.DoWhatever();
			this.screenOrientation = Screen.orientation;
		}
	}
	
	public void DoWhatever()
	{
		//These values are wrong
		this.wrongWidth = this.screenWidth;
		this.wrongHeight = this.screenHeight;
	}
	
	public void OnGUI()
	{
		//These are right
		string rightScreenSize = this.screenWidth.ToString() + "x" + this.screenHeight.ToString();
		GUI.Label(new Rect(Screen.width / 2, Screen.height / 2, 200, 50), "Right: " + rightScreenSize);
		
		//These are wrong
		string wrongScreenSize = this.wrongWidth.ToString() + "x" + this.wrongHeight.ToString();
		GUI.Label (new Rect(Screen.width / 2, Screen.height / 2 + 50, 200, 50), "Wrong: " + wrongScreenSize);
	}

Thanks for reading, I’d appreciate any help.

I’m guessing that is not related to the “DoWhatever” method call. I strong believe that if you move the two lines that are outside to inside the if you’ll get the same values. What I guess is that Android is changing the value of Screen.orientation in one frame and the actual values for Screen.width and Screen.height in the next frame.

Please, try this:

public void Update() {
    if (this.screenWidth != Screen.width || this.screenHeight = Screen.height) {
        this.screenWidth = Screen.width;
        this.screenHeight = Screen.height;
        this.DoWhatever();
    }
}