Score and Lives
Lesson 9 of 16 in Coddy's Unity Game: Brick Breaker course.
The score and the lives belong on the screen. The scene now has a Canvas with two TextMeshPro texts at the top, ScoreText and LivesText, and the GameManager holds them in TMP_Text fields from the TMPro namespace.
The numbers live in the GameManager's fields and the texts only show them. One method rewrites both texts from the fields, and every method that changes a number calls it, as does Start(), so the first frame shows the real values. A shop's coin counter:
public TMP_Text coinsText;
int coins;
public void AddCoins(int amount)
{
coins += amount;
ShowCoins();
}
void ShowCoins()
{
coinsText.text = "Coins: " + coins;
}The text changes only when the number does. Rewriting it in every Update() would look the same, but builds a new string each frame for nothing.
Challenge
Medium- Add
using TMPro;toGameManager, andpublic TMP_Text scoreTextandpublic TMP_Text livesText. The scene links ScoreText and LivesText. - Write
void ShowHud():scoreTextshowsScore: 0andlivesTextshowsLives: 3, with the current numbers. - Call
ShowHud()at the end ofStart(), and after the score or the lives change.
Press Play, break a brick, lose a ball, then Check.
Try it yourself
using UnityEngine;
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;
int score;
void Awake()
{
Instance = this;
}
void Start()
{
BuildWall();
}
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;
}
public void BallLost(Ball lost)
{
lives--;
lost.ResetToPaddle();
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.