Interacting with your UI elements

Bill Rislov
3 min readMay 4, 2021
Elements updating

The first thing we will need is a new script and add it to the Canvas. I will name the script UIManager.

Creating a script

In the UIManager script, we will need a reference to the Score text. Then use the serialized field attribute so we can assign it in the Inspector. now before we can work with the UI elements we will need to add Unity.UI library by adding the following code:

UnityEngine.UI
scoreText

Assign the Player_Score from the Canvas to the Score Text in the UIManager script.

Assigning the Player_Score

We will do the same for the Image element, well almost the same. Since the image needs to change based on the lives left, we will need to references one for the Player_lives image on the Canvas and one for the images that represent the different lives left(0, 1, 2 or 3), this is done by using [] to create an array that will hold the different images.

Reference to the Image element

Now we can assign the Player_Lives from the Canvas to the Lives Img in the UI Manager script. Next, we will set the size of the array, in my case, I will set it to 4 and assign the different sprites that represent the number of lives left.

We can now initialize the elements in the Start method and create the methods to update them during gameplay.

UI Manager Script

These methods will be called from the Player script and the score is updated from the Enemy script. This is done through the magic of Script Communication, which can be found in a previous article. When the enemy is destroyed the Enemy script will update the score on the player based on the point value of the enemy destroyed and the player script will send the Players total Score to the UI Manager.

Enemy updating the player score
Player call to the UIManager

Now in the Damage method on the Player script, we will add the logic to update the Player Lives on the UI Manager script to display the correct image on the Canvas.

UI Manager Lives Update

Ok now let's see how everything works together as we play the game.

Updating UI during game Play

Next article we will add a “Retro” style Game Over text when the Player is out of Lives. See you there.

Happy Coding :)

--

--