Visual Lives Represented by Hearts

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):

image

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.

1 Like

Also worth noting, that sprite sheet isn’t very good. Also my first attempt at doing something like that. I’ll be cleaning it up so it’s 3, 2, 1 instead of 2, 3, 1 haha. The slicing wasn’t very even either due to the gaps between the lines not being the same, so it jumps just slightly on the y axis but it’s hardly noticeable unless you’re looking for it.

Instead of using sprite sheet, instantiate single sprite multiple times as UI objects and set them disabled.
In run time, you could then toggle each one individually when health variable changes.

Privacy & Terms