Menu
CoddyTech

The Wall

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

The bricks stand in a grid: rows from the top down, columns left to right, each a copy of the Brick prefab made in two nested loops. One row first:

float left = -(columns - 1) * spacingX / 2f;
for (int col = 0; col < columns; col++)
{
    Vector3 pos = new Vector3(left + col * spacingX, topY, 0f);
    Instantiate(brickPrefab, pos, Quaternion.identity, wall);
}

Between n columns there are n minus 1 gaps, so the first one is half of (n - 1) * spacing to the left: 5 columns 2 apart stand at -4, -2, 0, 2 and 4. Each row goes spacingY lower than the last. The fourth argument of Instantiate is the parent, so every brick sits under the Wall object. With a script type such as Brick as the prefab field, Instantiate returns the new brick's script.

challenge icon

Challenge

Medium

Build a centered wall of bricks.

  1. In GameManager, add public Brick brickPrefab;, public Transform wall;, rows = 5, columns = 9, spacingX = 1.75f, spacingY = 0.75f, topY = 6f.
  2. BuildWall(): a brick under wall for each row and col, at x left + col * spacingX, y topY - row * spacingY, z 0, with left = -(columns - 1) * spacingX / 2f.
  3. Start() calls BuildWall().

Press Play: 45 bricks stand in a grid (they 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.
}

All lessons in Unity Game: Brick Breaker

Practice on your own: Unity playground