動作確認
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ごとの処理に変更した。