Menu
CoddyTech

Lives on Screen

Lesson 4 of 25 in Coddy's Unity Game: Tower Defense course.

The player should see the lives. The scene has a LivesText in the top bar, a TextMeshPro text. Its script type is TMP_Text, with using TMPro;, and what it shows is its text.

A text shows what it was last set to: it does not follow the variable. So put the line that shows the lives in one method, and call it wherever the lives change, so the screen never falls behind:

void ShowLives()
{
    livesText.text = "Lives: " + lives;
}
challenge icon

Challenge

Easy

Show the lives on screen.

  1. In GameManager, add using TMPro; and [SerializeField] private TMP_Text livesText;.
  2. Write ShowLives() as above.
  3. Call it at the end of Start and after the lives change.

Press Play: Lives: 20 drops as the enemies get through. Then Check.

Try it yourself

using UnityEngine;

public class GameManager : MonoBehaviour
{
    [SerializeField] private int startLives = 20;

    private int lives;

    void OnEnable()
    {
        Enemy.ReachedBase += OnReachedBase;
    }

    void OnDisable()
    {
        Enemy.ReachedBase -= OnReachedBase;
    }

    void Start()
    {
        lives = startLives;
    }

    void OnReachedBase(Enemy enemy)
    {
        lives -= enemy.data.damage;
    }
}

All lessons in Unity Game: Tower Defense

Practice on your own: Unity playground