Updating our Player’s Score
In the last article we created our Canvas UI — a place for our UI elements to live. We set up a Score text box, but it’s completely static right now.
In this article, we’ll be interacting with our Score through code, and updating in real-time when we destroy an Enemy!
The UIManager script
To handle our UI updates and the like, we’ll create a UIManager script and attach it to our Canvas.
Now inside of our UIManager script, we have to add a new namespace — UnityEngine.UI. This enables us to use Unity’s pre determined code for it’s UI elements. Interacting with our UI Canvas would be impossible without it.
Then we can create a handle for our Score text! It will be of type Text, and we’ll Serialize it so we can link in the Inspector.
In our Start() function we can initialize our Score text to be displayed. We can use a combination of strings and numbers, and soon variables.
Linking the correct Score text:
And our Score text initializing at Start:
Inside the Player script
There are many places we could store our Total Score within the game. You could choose to add it in the UI Manager, but I will be storing it in the Player script.
So we’ll create a _totalScore variable, and also a function to add to our _totalScore:
And since we’ll be interacting with our UI Manager, we’ll create a reference to it, and null check in the Start() function:
Interacting between the Scripts
We’ve created a reference to our UIManager in our Player script, but we’ll need a function to call from the UIManager to update our score display.
Create an UpdateScore(int totalScore) function. This requires an int to be passed in and be utilized.
This function will update our Score display with whatever int we pass through it.
Now we can alter our previous AddScore function inside the Player script:
Giving our Enemies some Score
We might want different enemies to have different Score values, so we’ll update the Enemy script to include a Point Value variable.
And we’ll create a reference to our Player:
Now we can reference our AddScore() function from our Player script. This makes the most sense when the Enemy is destroyed by our Laser:
If all was done correctly, we should be updating our Score in real-time! When the Enemy is destroyed, it calls the AddScore function from the Player, which in-turn calls the UpdateScore function in the UIManager. Good stuff!
In the next article we’ll be continuing in the UI section, by displaying our Player’s lives!