【Unity C#】ある条件になった時だけ実行可能にする(bool型)
boolでフラグを立てて、ある条件になったときだけ、実行可能にできるしくみを作ってみましょう。
キューブにぶつかれば、「Press EnterKey to Retry」が表示。
Enterキーを押すと、シーンが再ロードされてリトライできます。
ぶつかっていない時に、いくらEnterキーを押しても、リトライはできません。
テキストの準備
平面、Cube、Sphereのオブジェクトを用意して、色をつけました。
Cubeには、Finishのタグをつけ、トリガーにするにチェックを入れます。
テキストを作成して、テキスト名をRetryTextに。
テキストフィールドには「Press EnterKey to Retry」を入力します。
Canvasを選択し、画面の拡縮によって自動調整される「画面サイズに拡大」を選びました。
ゲームビューにはこのように配置されています。
テキストフィールドの文字は消しておきましょう。
boolによるフラグ設定
boolを使い、ぶつかり判定のtrue、falseをつくります。
まずは空のオブジェクトを作成しましょう。
TextControl.csを作成し、GameObjectに追加します。
TextControl.csを記述します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class TextControl : MonoBehaviour { public Text retryText; private bool isGameOver; void Start() { isGameOver = false; } public void Retry() { isGameOver = true; retryText.text = "Press EnterKey to Retry"; } void Update() { if (isGameOver == true) { if (Input.GetKey(KeyCode.Return)) { SceneManager.LoadScene("SampleScene"); } } } } |
GameObjectにRetryTextフィールドができたので、RetryTextを入れます。
プレーヤーのスクリプト
続いて、プレーヤー側を作成しましょう。
Sphereにリジッドボディを追加します。
PlayerMove.csを作成して、Sphereに追加します。
PlayerMove.csを記述しましょう。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMove : MonoBehaviour { public float speed; GameObject retryObject; void Start() { retryObject = GameObject.Find("GameObject"); } void Update() { float dx = Input.GetAxis("Horizontal") * Time.deltaTime * speed; float dz = Input.GetAxis("Vertical") * Time.deltaTime * speed; transform.position = new Vector3 ( transform.position.x + dx, 0.5f, transform.position.z + dz ); } void OnTriggerEnter(Collider collider) { if (collider.gameObject.tag == "Finish") { retryObject.GetComponent<TextControl>().Retry(); } } } |
速度のフィールドができるので、プレーヤーのスピードを入力します。
ゲームプレイして動きを確認しましょう。
Cubeに当たれば、「Press EnterKey to Retry」が表示されて、Eneterキーを押すとリトライできます。
「Press EnterKey to Retry」が出ていない間、Enterキーを押してもリトライできないことも確認しましょう。
スタート時、isGameOverはfalseに。
Cubeにぶつかった時、Retry()を実行して、isGameOverがtrueに変わります。
isGameOverがtrueになっている時だけ、Enterキーでシーンを再ロードできる仕組みです。
