Source file unity-csharp/arcade-classics/breakout/Brick.cs from the GDnD code examples. Download raw file
// GDnD wiki example
// Demonstrates: a single destructible object that takes hits, awards score, and reports its own death via an event
// Related pages: [[overview-arcade-classics-as-learning-projects]], [[observer-pattern]], [[unity-collider2d-and-triggers]]
using System;
using UnityEngine;
// One brick. It knows nothing about the grid or the score — it just takes hits,
// optionally changes colour as it weakens, and raises Destroyed when it dies.
// The grid listens; this keeps each object's responsibility small.
[RequireComponent(typeof(Collider2D), typeof(SpriteRenderer))]
public class Brick : MonoBehaviour
{
[SerializeField] private int hitPoints = 1;
[SerializeField] private int scoreValue = 100;
// Passes its own score value so the grid/game can tally without inspecting the brick.
public event Action<int> Destroyed;
private SpriteRenderer spriteRenderer;
private Color baseColour;
private void Awake()
{
spriteRenderer = GetComponent<SpriteRenderer>();
baseColour = spriteRenderer.color;
}
// Called by the ball on contact. Returns true if the brick survived.
public bool Hit()
{
hitPoints--;
if (hitPoints > 0)
{
// Darken as it weakens so multi-hit bricks read clearly — cheap [[game-feel]].
spriteRenderer.color = baseColour * 0.6f;
return true;
}
Destroyed?.Invoke(scoreValue);
Destroy(gameObject);
return false;
}
}