3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

unity > androidアプリ > deviceOrientation(端末の向き)の変化を検知する > Coroutineでチェック

Last updated at Posted at 2015-08-23
動作確認
Unity 5.1.2-f1 on MacOS X 10.8.5

android端末の向きを変えた時にそれを検知したい。

http://forum.unity3d.com/threads/device-screen-rotation-event.118638/
のJessyの実装を使う(一部変更)。

	IEnumerator CheckScreenRotation() {
		while (true) {
			switch (Input.deviceOrientation) {
			case DeviceOrientation.Unknown:
			case DeviceOrientation.FaceUp:
			case DeviceOrientation.FaceDown:
				yield return null;
				break;
			default:
				if (Screen.orientation != (ScreenOrientation)Input.deviceOrientation) {
					SetScreenResolution ();
				}
				yield return null;
				break;
			}
		}
	}

上記をコルーチンとして呼び出すことにより、端末の向きが切り替わった時にSetScreenResolution()がコールされる。

上記を含めての画面サイズ調整の処理は以下。

MainCameraControl.cs
using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class MainCameraControl : MonoBehaviour {
	
	public Text msgText; // set Text to show message
	public Button myButton; // set UI>Button whose width is used as standard

	void SetScreenResolution()
	{
		float aspect = (float)Screen.height / (float)Screen.width;
		float buttonRatio = 0.25f; // 25%
		int buttonWidth = (int)myButton.GetComponent<RectTransform> ().rect.width;
		float newWidth, newHeight;
		
		newWidth = buttonWidth / buttonRatio;
		newHeight = newWidth * aspect;
		
		Screen.SetResolution ((int)newWidth, (int)newHeight, false);
		msgText.text = newWidth.ToString () + "x" + newHeight.ToString ();
	}

	void Start () {
		SetScreenResolution ();
		StartCoroutine ("CheckScreenRotation");
	}	
	
	IEnumerator CheckScreenRotation() {

		while (true) {
			switch (Input.deviceOrientation) {
			case DeviceOrientation.Unknown:
			case DeviceOrientation.FaceUp:
			case DeviceOrientation.FaceDown:
				yield return new WaitForSeconds(0.1f);
				break;
			default:
				if (Screen.orientation != (ScreenOrientation)Input.deviceOrientation) {
					SetScreenResolution ();
				}
				yield return new WaitForSeconds(0.1f);
				break;
			}
		}
	}

}

MainCameraControl.csにより、端末がどの向きでもButtonのwidthが画面の25%となるように画面サイズが調整される。

コルーチン処理の重さを軽くするため100msecごとの処理に変更した。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?