Score and Lives
Lesson 9 of 19 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
MediumShow the score and the lives on screen.
- In
GameManager, addusing TMPro;,public TMP_Text scoreText;andpublic TMP_Text livesText; - Write
void ShowHud():scoreText.text = "Score: " + score;andlivesText.text = "Lives: " + lives; - Call
ShowHud()at the end of Start, in BrickBroken and in BallLost.
Press Play: Score: 0 and Lives: 3 show, and change as you play. 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();
}
}
All lessons in Unity Game: Brick Breaker
Practice on your own: Unity playground