Menu
CoddyTech

Lose a Ball

Lesson 8 of 16 in Coddy's Unity Game: Brick Breaker course.

A ball that gets past the paddle is lost. Below the paddle the scene now has a DeathZone: an object with a box collider set to Is Trigger and the tag DeathZone. A trigger stops nothing; it sends OnTriggerEnter(Collider other) when something with a Rigidbody enters it. The ball reports the loss to the GameManager, which owns the lives and decides what happens next.

A marble that falls in the water starts again at its spawn point:

void OnTriggerEnter(Collider other)
{
    if (other.CompareTag("Water")) Respawn();
}

void Respawn()
{
    rb.linearVelocity = Vector3.zero;
    transform.position = spawnPoint.position;
}

The ball needs less than the marble. Its Update() already puts it on the paddle every frame while launched is false, so a reset only has to clear that flag and stop the ball: the next frame carries it back, and Space launches it again.

challenge icon

Challenge

Medium
  1. In Ball, write public void ResetToPaddle(): the ball is no longer launched and stops moving.
  2. Add OnTriggerEnter to Ball: when it enters the object tagged DeathZone, call GameManager.Instance.BallLost(this).
  3. In GameManager, add public int lives = 3 and public void BallLost(Ball lost): one life fewer, and the lost ball goes back on the paddle.

There is no game over yet, so the lives go on below 0 for now.

Press Play, miss the ball on purpose, launch again, then Check.

Try it yourself

using UnityEngine;

public class GameManager : MonoBehaviour
{
    public static GameManager Instance;

    public Brick brickPrefab;
    public Transform wall;
    public int rows = 5;
    public int columns = 9;
    public float spacingX = 1.75f;
    public float spacingY = 0.75f;
    public float topY = 6f;
    public int[] rowHits = { 2, 1, 1, 1, 1 };

    int score;

    void Awake()
    {
        Instance = this;
    }

    void Start()
    {
        BuildWall();
    }

    void BuildWall()
    {
        float left = -(columns - 1) * spacingX / 2f;
        for (int row = 0; row < rows; row++)
        {
            for (int col = 0; col < columns; col++)
            {
                Vector3 pos = new Vector3(left + col * spacingX, topY - row * spacingY, 0f);
                Brick brick = Instantiate(brickPrefab, pos, Quaternion.identity, wall);
                brick.SetHits(rowHits[row]);
            }
        }
    }

    public void BrickBroken(Brick brick)
    {
        score += brick.points;
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Unity Game: Brick Breaker