Game Over
Lesson 12 of 16 in Coddy's Unity Game: Brick Breaker course.
The last lost life ends the game. The ball leaves play, a Game Over panel covers the screen, and its Play Again button starts a new game. The scene now has the panel, hidden, inside the HUD canvas, and the button's On Click list in the Inspector already calls GameManager.PlayAgain. The On Click list only offers public methods, so the method you pick for a button must be public.
The simplest new game is the scene loaded again. Every object is made fresh from the scene: a new GameManager with score 0 and 3 lives, a new wall, the ball back on the paddle. The scene that is playing is SceneManager.GetActiveScene(), and its buildIndex is its number in the build:
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);Hiding the ball with SetActive(false) stops its Update(), so Space can no longer launch it, and takes it out of the physics. The test comes after lives--, so the game ends when lives reaches 0: the third lost ball when lives starts at 3.
Challenge
Medium- Add
using UnityEngine.SceneManagement;andpublic GameObject gameOverPaneltoGameManager. The scene links the hidden GameOverPanel. - In
BallLost, when the last life is gone, show the panel and hide the lost ball withSetActive(false), instead of putting it back on the paddle. - Write
public void PlayAgain(), which loads the scene that is playing again. The panel's Play Again button already calls it.
Press Play, lose all three balls, click Play Again, then Check.
Try it yourself
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;
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.