Levels From Text
Lesson 11 of 19 in Coddy's Unity Game: Brick Breaker course.
A game with levels needs a way to write them down. Text is the easiest: one character per brick, one string per row. Here a digit is a brick with that many hits, a dot is a gap, and a level's rows go in one string split by /, so the scene's levels holds three layouts and the first is today's wall.
string[] rows = "1.1/22".Split('/'); // "1.1" and "22"
char c = rows[1][0]; // '2'A digit character is not its number: '3' is a char whose code is 51. The digits have codes in order, so taking away '0' gives the number: '3' - '0' is the int 3. Each row is centered on its own length, -(line.Length - 1) * spacingX / 2f.
Challenge
MediumBuild the wall from text, such as 3.3.3/22222.
- In
GameManager, remove rows, columns and rowHits; addpublic string[] levels;andint level; - Replace BuildWall() with
BuildLevel(int index): store index in level, splitlevels[index]at'/', and for each digitcbuild a centered brick withSetHits(c - '0'); a dot is a gap. Start()callsBuildLevel(0).
Press Play: the same wall, now built from the first level's text. Then Check.
Try it yourself
using UnityEngine;
using TMPro;
public class GameManager : MonoBehaviour
{
public static GameManager Instance;
public Brick brickPrefab;
public Transform wall;
public int rows = 5;
public int columns = 9;
public float spacingX = 1.75f;
public float spacingY = 0.75f;
public float topY = 6f;
public int[] rowHits = { 2, 1, 1, 1, 1 };
public int lives = 3;
public TMP_Text scoreText;
public TMP_Text livesText;
int score;
void Awake()
{
Instance = this;
}
void Start()
{
BuildWall();
ShowHud();
}
void BuildWall()
{
float left = -(columns - 1) * spacingX / 2f;
for (int row = 0; row < rows; row++)
{
for (int col = 0; col < columns; col++)
{
Vector3 pos = new Vector3(left + col * spacingX, topY - row * spacingY, 0f);
Brick brick = Instantiate(brickPrefab, pos, Quaternion.identity, wall);
brick.SetHits(rowHits[row]);
}
}
}
public void BrickBroken(Brick brick)
{
score += brick.points;
ShowHud();
}
public void BallLost(Ball lost)
{
lives--;
ShowHud();
lost.ResetToPaddle();
}
void ShowHud()
{
scoreText.text = "Score: " + score;
livesText.text = "Lives: " + lives;
}
}
All lessons in Unity Game: Brick Breaker
Practice on your own: Unity playground