120 Days to master Unity. (Day 6)

Displaying lives

One thing my current game is missing now that most games used to have is a lives counter. This can be fixed easily with Unity using Unity’s built-in UI image game object. They key to displaying an image of player’s lives on the screen is being able to get a reference to the variable that holds the image that will change throughout the game in real time while the player is loosing lives until the end of the game.

The first thing that needs to be done is to create an UI image game object. This can be done by clicking on GameObject in the menu, clicking UI, and then clicking on image.

If there is no canvas game object yet, one will be created when creating the UI image. The UI image needs to be a child of the Canvas game object for all this to work.

The UI image and the variable that hold’s its vale is the key to making the lives counter work. A variable needs to be created in a UI Manager script first of all, to hold the value of the UI image. This variable needs to first be an Image variable. It also must be serialized and private like all class variables. Making the variable a serialized field in the UI manager script will allow the UI image in the editor to be dragged into the UI image variable slot on the editor.

After the image is dragged into the image variable slot, we now have a reference to that image file dragged into our image variable in the script. This is important because it gives the script a reference to the image that was just dragged in which allows that image to be changed into another sprite image.

The next thing to do is find an sprite image to put onto that UI image that will stand for player lives. You can find any image and drag it into source image of the UI image slot. No variable or script needs to be created for this slot. Its automatically created when the UI image is created.

The image needs to be placed on the screen. In my case, I placed the image and anchored it to the upper right hand corner of the screen.

With the reference I have now to the UI image. I can change the source image sprite on that UI image. The following code shows how I can change the image based on the player lives. I first start in the Player script where the damage the player takes is tracked.

Sending damage to the display

When the player takes damage, it can be tracked with the _damage variable which is the total amount of damage that can be taken minus the damage taken so far. This is then sent to the UI manger method displayPlayerLives() to determine what gets shown on the screen. The logic below shows how the image changes depending on how much damage is sent over from the Player script.

Now, the sprites are cycled from no damage to no points left on damage and the player is destroyed.