脳汁portal

アメリカ在住(だった)新米エンジニアがその日学んだIT知識を書き綴るブログ

Unityでコントローラを利用したセレクト画面の作り方2(Submit取得の改良)

前回

前回のポストではクリック情報を取得するために、

1. ButtonFunction.csスクリプトを作成
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;

public class ButtonFunction : MonoBehaviour {

	public void StringArgFunction(string s){
		SceneManager.LoadScene (s);
	}
}
2. スクリプトをAttachする空GameObjectの作成

f:id:portaltan:20160510093930p:plain

3. ボタンのuGUIからOnClickイベントの登録

f:id:portaltan:20160510093637p:plain

という手順を踏んでいましたが、少し手順が多く面倒に感じ、スクリプト側で処理をまとめられないかと思い少し改良しました

今回

大元のmenu.csを以下のように変更します

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.EventSystems;    // 追加(get EventSystem(Hierarchy) action)
using UnityEngine.SceneManagement; // 追加(enable to use change scene(latest))

public class menu : MonoBehaviour {
	Button cube;
	Button sphere;
	Button cylinder;

	void Start () {
		cube     = GameObject.Find ("/Canvas/Button1").GetComponent<Button> ();
		sphere   = GameObject.Find ("/Canvas/Button2").GetComponent<Button> ();
		cylinder = GameObject.Find ("/Canvas/Button3").GetComponent<Button> ();

		cube.Select ();
	}


        // ↓ここから追加
	void Update() {
                // ボタンが押されたら・・・
		if (OVRInput.GetUp(OVRInput.Button.Start)){

                        // 選択中のオブジェクト情報を取得
			GameObject selectedButton = EventSystem.current.currentSelectedGameObject;

                        // オブジェクトの名前で条件分岐して
			switch (selectedButton.name) {
			case "Button1":
				Debug.Log ("Pushed Button1");
                                // 該当のシーンへ飛ばす
				SceneManager.LoadScene ("Cube");
				break;
			case "Button2":
				Debug.Log ("Pushed Button2");
				SceneManager.LoadScene ("Sphere");
				break;
			case "Button3":
				Debug.Log ("Pushed Button3");
				SceneManager.LoadScene ("Cylinder");
				break;
			}
		}
	}
}


不要な以下のファイル/オブジェクト/イベント処理は削除します

  • ButtonFunction.cs
  • 空GameObject
  • それぞれのButtonで登録していたOnClick()イベント

セレクトシーンに戻る機能

ついでにセレクト画面に戻る機能も追加しました

using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement; // enable to use change scene(latest)

public class back : MonoBehaviour {

	// Update is called once per frame
	void Update () {
		if (OVRInput.GetUp(OVRInput.Button.Back)){
			SceneManager.LoadScene ("select");
		}
	}
}

これをCube/Sphere/CylinderシーンのOVRCameraRigにAttachします

  • (OVRInputはMainCameraでは使えません)