おさらい:ラウンドマネージャー
CoddyのUnityジャーニー「本格的なゲームを作る」セクションの一部。レッスン 16/60。
この章では、ゲームに1つのマネージャーを用意しました。これは、他のオブジェクトがフィールドを使わずにアクセスできるシングルトンであり、切り替わる状態を持っています。ラウンドマネージャーは、この両方を活用します。
チャレンジ
簡単コイン集めを完成させましょう。SetStateは記述済みです。
public static RoundManager Instance;を追加し、Awake()で設定します。Update()でstateを切り替えます。ReadyではSpaceキーを待ち、PlayingではtimeLeftをカウントダウンし、その後、次のReadyに進むか、最後のラウンドの後にFinishedに進みます。public bool TakeCoin():Playing中のみコインを数え、Coins: 2と表示して、trueを返します。Coin.csは、Playerが触れた、数えられたコインを破棄します。
3ラウンドすべてで「プレイ」を押します。その後、「確認」を押します。
自分で試してみよう
using UnityEngine;
using TMPro;
public enum RoundState { Ready, Playing, Finished }
public class RoundManager : MonoBehaviour
{
// シングルトン: static な Instance。Awake() で設定する
public GameObject readyPanel;
public GameObject playPanel;
public GameObject finishedPanel;
public TMP_Text roundText;
public TMP_Text coinsText;
public TMP_Text finalText;
public int rounds = 3;
public float roundTime = 4f;
private RoundState state;
private int round = 1;
private int coins;
private float timeLeft;
void Start()
{
SetState(RoundState.Ready);
}
void Update()
{
// state に応じて分岐する: Ready では Space の入力を待ち、Playing では残り時間をカウントダウンする
}
void SetState(RoundState next)
{
state = next;
readyPanel.SetActive(next == RoundState.Ready);
playPanel.SetActive(next == RoundState.Playing);
finishedPanel.SetActive(next == RoundState.Finished);
if (next == RoundState.Ready) roundText.text = "Round " + round;
if (next == RoundState.Playing) timeLeft = roundTime;
if (next == RoundState.Finished) finalText.text = "Coins: " + coins;
}
// TakeCoin(): コインがカウントされるのは Playing 中だけ
}
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
本格的なゲームを作るのすべてのレッスン
自分で練習してみよう: Unityプレイグラウンド