Menu
CoddyTech

Tough Bricks

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

Some bricks take more than one hit. Each brick keeps a count of the hits it has left: a hit takes one away, and only the hit that brings it to 0 breaks the brick and scores. Until then the brick changes color, so the player can see how tough it still is.

An array of colors filled in the Inspector maps the count to a color. Element 0 is the color for one hit left, element 1 for two, so the color for a count of n is element n - 1. A shield with charges does the same:

public Color[] chargeColors;   // element 0: 1 charge left

void ShowCharges(int charges)
{
    GetComponent<Renderer>().material.color = chargeColors[charges - 1];
}

Reading material gives this renderer its own copy of the material the first time, so one shield, or one brick, changes color without repainting every copy of the prefab. The GameManager decides how tough each new brick is: an int[] with one number per row, top row first, lets the top row take more hits than the rest.

challenge icon

Challenge

Medium
  1. In Brick, add public int hits = 1 and public Color[] colors. The scene fills colors with blue, orange and red, for 1, 2 and 3 hits left.
  2. Write public void SetHits(int count): it sets hits and shows the brick's color for it.
  3. Change Hit(): take one away from hits. At 0 the brick breaks and scores as before; otherwise it only shows its new color.
  4. In GameManager, add public int[] rowHits = { 2, 1, 1, 1, 1 }; and give each new brick rowHits[row] hits with SetHits.

Press Play, wear down an orange brick in the top row, then Check.

Try it yourself

using UnityEngine;

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

    void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.CompareTag("Ball")) Hit();
    }

    public void Hit()
    {
        GameManager.Instance.BrickBroken(this);
        Destroy(gameObject);
    }
}
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