Instead of a counter for lives I implemented a visual representation. I ended up getting it to work by using a script attached to the canvas, then watched this episode fully and changed the implementation to be pretty much like this but with an image instead of a text object under the canvas.
Here’s what it looks like in game:
I did this by having a sprite sheet with three sprites sliced up (capping the lives to 3 for now):
I added a few SerializeField’s to GameSession.cs:
[SerializeField] Image health;
[SerializeField] Sprite threeHearts;
[SerializeField] Sprite twoHearts;
[SerializeField] Sprite oneHeart;
Then added the sprites and image in the Inspector for the object GameSession. Just like the score text field is done.
Then I changed my SubtractLife() method to look like this, adding the if/else grouping:
private void SubtractLife() {
playerLives--;
if(playerLives == 2) {
health.sprite = twoHearts;
} else if(playerLives == 1) {
health.sprite = oneHeart;
}
var currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
SceneManager.LoadScene(currentSceneIndex);
}
I haven’t thought out what I’d do if the game were to add lives back, but I think I’d just need more sprites and add to the SerializeField’s and the if/else statement I have going on.