回顾:回合管理器
本课属于 Coddy Unity 学习旅程的“打造真正的游戏”单元。第 16 课,共 60 课。
这一章为游戏添加了一个管理器:一个单例,其他对象无需通过字段就能访问它;它还包含多个状态,并会在这些状态之间切换。回合管理器会用到这两者。
挑战
简单完成收集金币的挑战;SetState 已写好。
- 添加
public static RoundManager Instance;,并在Awake()中设置。 - 在
Update()中,根据state进行切换:Ready 等待按下空格键;Playing 让timeLeft倒计时,然后进入下一轮 Ready,最后一轮结束后进入 Finished。 public bool TakeCoin():仅在 Playing 状态下计数,显示Coins: 2,并返回 true。玩家碰到已计数的金币时,Coin.cs会销毁它。
按“开始”完成全部三轮,然后按“检查”。
亲手试试
using UnityEngine;
using TMPro;
public enum RoundState { Ready, Playing, Finished }
public class RoundManager : MonoBehaviour
{
// 单例:静态的 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 在线编辑器