Menu
CoddyTech

The Wall

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

The bricks stand in a grid: rows from the top down, columns from left to right, each a copy of a brick prefab made in two nested loops. A brick's position comes from its row and column numbers times the spacing between brick centers, which is a brick's size plus a small gap.

To center a grid on x = 0, work out where the first column goes. Between n columns there are n minus 1 gaps, so with a spacing of s the outer centers are (n - 1) * s apart, and the first one is half of that to the left. Five fence posts, 2 units apart:

int posts = 5;
float spacing = 2f;
float left = -(posts - 1) * spacing / 2f;
for (int i = 0; i < posts; i++)
{
    Instantiate(postPrefab, new Vector3(left + i * spacing, 0f, 3f), Quaternion.identity);
}

They stand at -4, -2, 0, 2 and 4: the first post is at -4, not -5, because four gaps separate five posts. Instantiate's fourth argument, a parent Transform, puts each copy under one object so the Hierarchy stays tidy. When the prefab field's type is a script, such as Brick, Instantiate returns the new copy's script, ready to use.

challenge icon

Challenge

Medium

Build the wall in GameManager:

  1. Add public Brick brickPrefab and public Transform wall (the scene links the Brick prefab and the Wall object), and public int rows = 5, public int columns = 9, public float spacingX = 1.75f, public float spacingY = 0.75f and public float topY = 6f.
  2. Write void BuildWall(): a brick for every row and column, made a child of wall. Row 0 is at y = topY and each row is spacingY lower. The columns are spacingX apart and centered on x = 0. The bricks sit at z = 0.
  3. Call BuildWall() from Start().

Press Play and bounce the ball off the wall (the bricks do not break yet), then Check.

Try it yourself

using UnityEngine;

public class GameManager : MonoBehaviour
{
    public static GameManager Instance;

    void Awake()
    {
        Instance = this;
    }

    // Later: the wall of bricks, the score, the lives and the levels.
}
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