Menu
CoddyTech

Break

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

The bricks have no Rigidbody, but the ball has one, and Unity sends OnCollisionEnter to both objects in a collision. So a brick can notice the hit itself. In the brick's script, gameObject is the brick and collision.gameObject is the thing that hit it.

The score belongs to the GameManager, and bricks are copies of a prefab. A prefab is an asset outside the scene, so its fields cannot point at the scene's GameManager in the Inspector. The GameManager sets the static GameManager.Instance to itself in Awake(), so any script can reach it, prefab copies too.

A vase that shatters when the player runs into it:

void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.CompareTag("Player")) Shatter();
}

public void Shatter()
{
    Destroy(gameObject);
}

Destroy(gameObject) removes the vase. Destroy(collision.gameObject) would remove the player, and Destroy(this) removes only the script, leaving the vase standing. Keeping the break in its own public method means other code, a bomb or a power-up, can break the vase too.

challenge icon

Challenge

Medium
  1. In GameManager, add an int score and public void BrickBroken(Brick brick), which adds the brick's points to score.
  2. In Brick, write public void Hit(): it tells GameManager.Instance that this brick broke, then destroys the brick.
  3. Add OnCollisionEnter to Brick: when the object tagged Ball hits it, call Hit().

Press Play, break a few bricks, then Check.

Try it yourself

using UnityEngine;

public class Brick : MonoBehaviour
{
    public int points = 10;

    // Next: the ball breaks a brick and scores its 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