Menu
CoddyTech

Next Level

Lesson 12 of 19 in Coddy's Unity Game: Brick Breaker course.

A level is cleared when its last brick breaks. Count: add one for every brick built, take one away for every brick broken, and at 0 the level is done.

Counting the bricks still in the scene does not work at that moment: Destroy waits for the end of the frame, so the brick that is breaking is still there.

After the last level comes the first again. The remainder of a division wraps a number round:

int next = (2 + 1) % 3;   // 0: after index 2 of 3 levels, back to 0

The ball goes back on the paddle first, so the new wall does not start under a flying ball.

challenge icon

Challenge

Medium

Clearing the bricks builds the next level.

  1. In GameManager, add public Ball ball; (the scene links it) and int bricksLeft;; BuildLevel adds one for each brick it builds.
  2. BrickBroken takes one off bricksLeft. At 0, call ball.ResetToPaddle(); and BuildLevel((level + 1) % levels.Length);

Press Play and clear a level: the ball waits on the paddle and a new wall appears. 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 int lives = 3;
    public TMP_Text scoreText;
    public TMP_Text livesText;

    int score;
    int level;

    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');
            }
        }
    }

    public void BrickBroken(Brick brick)
    {
        score += brick.points;
        ShowHud();
    }

    public void BallLost(Ball lost)
    {
        lives--;
        ShowHud();
        lost.ResetToPaddle();
    }

    void ShowHud()
    {
        scoreText.text = "Score: " + score;
        livesText.text = "Lives: " + lives;
    }
}

All lessons in Unity Game: Brick Breaker

Practice on your own: Unity playground