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
MediumBuild the wall in GameManager:
- Add
public Brick brickPrefabandpublic Transform wall(the scene links the Brick prefab and the Wall object), andpublic int rows = 5,public int columns = 9,public float spacingX = 1.75f,public float spacingY = 0.75fandpublic float topY = 6f. - Write
void BuildWall(): a brick for every row and column, made a child ofwall. Row 0 is at y =topYand each row isspacingYlower. The columns arespacingXapart and centered on x = 0. The bricks sit at z = 0. - Call
BuildWall()fromStart().
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.
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.