Framework 1: Collectables
Time to work with collectable game objects and adding in a UI element which gives players feedback on Lives, and score/coin count.
Preparing the UI:
First lets create an new Canvas which will house all of our UI elements. I created an Text object which will contain our data for the lives and coin count.
I made sure that the text is on the top left with the Canvas render mode set to “Screen Space — Overlay” and the Canvas Scaler set to “Scale with Screen Size”. Then for the text, I just temporary write “Score” but this will be adjusted in the score script.
The scripting is going to be based on two parts, the Player script which will house all the collectable data and score data. Then there is the UI manager script which will control what the UI elements display. These two scripts will be communicating with each other.
In the player script, we will start by create a new local variable called _coins. (or whatever the player is going to collect, it can also be called points) We are also going to add an Serialized Field to it so we can adjust it within the Inspector.
Next we are going to create two public methods which will allow the communication between the player script, UI manager script and Collectable script(which we will add later). The first public method is going to be a return script which basically gives the UI manager script the access to the total amount of coins the player has collected.
The second public method is the communication between the Player script and the collectable script (which will be our collectable, ie. coins etc.) What this public method does, is basically add and point/coin by the value of 1, then Updates the total amount to the UI manager.
UI Manager Script:
In the UI manager Script, if you haven’t created one already, right click and create new C# script to create one. Before start scripting within the UI manager, we first need to gain access to the UI library. The UI library as access to all the UI elements such as Text and image etc.
Start by creating an Serialized Field of the private Text object. In this case I only want the coin Text (or points text). This will allow us to drag and drop the text element from the UI into the script.
Then create a new public method called “Update Coin Display” with an integer variable attached called “coins”. What we want is to have the coin text element equal the string name “Coins:” plus the value accessed from the player script.
Back in Unity, save and play the scene and you will quickly noticed that the UI score text will be updated according to the UI manager script. In part 2, we will focus on creating the collectables which will update the UI manager and also player script.