Interactive Interaction — Building a User Interface
Players need information in order to engage with a medium. Videogame UI have been around as long a Pong, and that’s a long time!
In the 2D example game I have been constructing, the player shoots at enemies and collects powerups.
A helpful piece of information would be a score system, so let’s build one!
First off, we need a Canvas. A Canvas is a container for all UI elements in Unity.
When a canvas is created, Unity will automatically create an Event System as well.
You need an event system for any UI elements to work, do not delete it!
Now we can add a new text element and name it score_text.
In the Inspector, set the Text box to “Score:”. You may also change the text color, position, font, and size.
Now position your score where you want it in the Scene view. I placed mine in the top right corner.
Your game view will show your text wherever you placed it!
So how we do update the score? Well we will need a UI Manager to start. I use the Canvas as my UI manager, but often times there will be a dedicated UI Manager gameobject, much like the spawn manager.
Create a new C# script and name is appropriately (UIManager).
Attach this script to your UI manager in the hierarchy window
Inside the C# script we need to add a few things to the library at the very top of the script.
Add lines 4 and 5 so we can set up the UI.
Inside this script we need to know what the Score Text is, so we add it as a variable. We also will need to know what the player is, so add that as well!
Now in Void Start we will set our player variable and the default value of our scoreText.
We will make a new function to update the score, called UpdateScore.
Now, when do we want to all this function? When the player destroys an enemy with their laser specifically!
So our player needs to have an integer variable to hold their score, and a function to increase it.
Then, the enemy needs to call that function.
Finally, the player needs to send the updated score to the UI manager!
With all of that put together, the score counter should increment by 10 for each enemy ship we destroy!