游戏结束
Coddy Unity 游戏:打砖块 课程的第 13 课,共 19 课。
最后一条生命用完时,游戏结束。球离开游戏区域,“游戏结束”面板覆盖屏幕,面板上的“再玩一次”按钮会开始新游戏。现在,HUD 画布中有一个隐藏的面板,检查器中的按钮“点击时”列表已经调用了 GameManager.PlayAgain。点击时列表只提供 public 方法,所以你为按钮选择的方法必须是 public。
开始新游戏最简单的方法是重新加载场景。场景中的所有对象都会重新创建:一个分数为 0、生命数为 3 的新 GameManager、一面新墙,以及回到挡板上的球。当前正在运行的场景是 SceneManager.GetActiveScene(),它的 buildIndex 是它在构建列表中的编号:
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);使用 SetActive(false) 隐藏球会停止它的 Update(),因此空格键无法再发射它,而且它也会退出物理模拟。检查发生在 lives-- 之后,所以生命数降到 0 时游戏结束:如果初始生命数为 3,那么第三个球丢失时游戏结束。
挑战
中等失去最后一条命后,游戏就会结束,点击“再玩一次”即可重新开始。
- 在
GameManager中,添加using UnityEngine.SceneManagement;和public GameObject gameOverPanel; - 在 BallLost 中,当
lives == 0时,显示面板并用lost.gameObject.SetActive(false)隐藏球;否则,像之前一样重置它。 - 编写
public void PlayAgain():SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
点击运行,让 3 个球都失去后,再点击再玩一次:新游戏就会开始。然后点击检查。
亲手试试
using UnityEngine;
using TMPro;
public class GameManager : MonoBehaviour
{
public static GameManager Instance;
public Brick brickPrefab;
public Transform wall;
public string[] levels;
public float spacingX = 1.75f;
public float spacingY = 0.75f;
public float topY = 6f;
public Ball ball;
public int lives = 3;
public TMP_Text scoreText;
public TMP_Text livesText;
int score;
int level;
int bricksLeft;
void Awake()
{
Instance = this;
}
void Start()
{
BuildLevel(0);
ShowHud();
}
void BuildLevel(int index)
{
level = index;
string[] rows = levels[index].Split('/');
for (int row = 0; row < rows.Length; row++)
{
string line = rows[row];
float left = -(line.Length - 1) * spacingX / 2f;
for (int col = 0; col < line.Length; col++)
{
char c = line[col];
if (c == '.') continue;
Vector3 pos = new Vector3(left + col * spacingX, topY - row * spacingY, 0f);
Brick brick = Instantiate(brickPrefab, pos, Quaternion.identity, wall);
brick.SetHits(c - '0');
bricksLeft++;
}
}
}
public void BrickBroken(Brick brick)
{
score += brick.points;
bricksLeft--;
ShowHud();
if (bricksLeft == 0)
{
ball.ResetToPaddle();
BuildLevel((level + 1) % levels.Length);
}
}
public void BallLost(Ball lost)
{
lives--;
ShowHud();
lost.ResetToPaddle();
}
void ShowHud()
{
scoreText.text = "Score: " + score;
livesText.text = "Lives: " + lives;
}
}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
Unity 游戏:打砖块中的所有课
自己练习: Unity 在线编辑器