Tough Bricks
Lesson 7 of 19 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
MediumTop-row bricks take two hits.
- In
Brick, addpublic int hits = 1;,public Color[] colors;(the scene sets blue, orange, red) andSetHits(int count): set hits and the colorcolors[hits - 1]. Hit()takes one off hits: at 0 it breaks and scores, else it shows the new color.- In
GameManager, addpublic int[] rowHits = { 2, 1, 1, 1, 1 };and callbrick.SetHits(rowHits[row])on each new brick.
Press Play: the top row is orange and turns blue when hit. 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);
}
}
All lessons in Unity Game: Brick Breaker
Practice on your own: Unity playground