Ease of Building UI Elements in Unity With a Score System — Part 02
Objective: Adding scripting to our UI Element so the Score will update during gameplay!
Note: From the previous article I have gone back and made some adjustments to some settings so the Score stands out a bit more. The settings are now:
Position X: -250, Position Y: -80, Font Size: 50 and Vertical Overflow has been changed to ‘Overflow’.
Adding a UI Script to our UI Elements
First off here we are going to jump into our ‘Player’ script as we need to create a variable that is going to track our score and also we need to create a method that is going to increment the score when the laser hits the enemy.
Make sure it is a public access modifier so we can find it in the ‘Enemy’ script.
Now, we need to head over to the ‘Enemy’ script where we are going to use script communication to call this method from when the laser collides with the enemy in the OnTriggerEnter2D() method:
Communicating With the UI to Update the Score
Let’s now get the score to talk with the UI and have it updating on our screen. Firstly, within our ‘UIManager’ script, lets create a method that is going to take our score from the Player and assign it to the text box:
Here, we have created a new variable called _scoreText of type Text. It will give you an error as type Text belongs to the UnityEngine.UI namespace and this needs to be added to the namespaces at the top for it to be accessible.
Make sure to now add the Score_Text game object to the newly created variable in the Inspector on the Canvas under UIManager:
Head back over to the ‘Player’ script and we are now going to create a reference to the ‘UIManager’ script so we can take our score and add it into a method that is read by the ‘UIManager’ script so it updates:
Here, we have created a reference to the ‘UIManager’ script to allow for script communication. We then get the UIManager component by finding it on the game object and null checking.
Next, we need to access the UpdateScore() method in the UIManager and provide an int parameter (_score) as we have made this a condition.
WE HAVE A FUNCTIONING SCORE SYSTEM!!!
Adding a more Randomized Scoring System
As you can see above, the score that is being displayed isn’t the 10 points that we put in the original parameter as I wanted to add a bit more variety to the game by making this a random number. To get started in making these changes, firstly within the AddScore() method we are going to give it a new parameter which is ‘int points’:
So now the AddScore() method within the ‘Enemy’ script, is going to show us an error as we haven’t met the condition of the new parameter:
We could simply add in this parameter ‘10’ again and it would work perfectly fine, but we wanted to randomize it so let’s now use Random.Range: