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
Medium- In
Brick, addpublic int hits = 1andpublic Color[] colors. The scene fillscolorswith blue, orange and red, for 1, 2 and 3 hits left. - Write
public void SetHits(int count): it setshitsand shows the brick's color for it. - Change
Hit(): take one away fromhits. At 0 the brick breaks and scores as before; otherwise it only shows its new color. - In
GameManager, addpublic int[] rowHits = { 2, 1, 1, 1, 1 };and give each new brickrowHits[row]hits withSetHits.
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);
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.