Building UI in Unity (Game Dev Day 21)
Our game is playable in its current state, but there is no HUD or UI to inform the player of their lives, or how many enemy ships they have destroyed. Fortunately, Unity makes UI development pitifully easy.
Lets begin with a “score” system that gives our player 10 points every time they destroy an enemy with their laser.
First, lets make the actual UI element, then we will get into the logic and coding to make it automatically update when we destroy an enemy.
By right clicking in our hierarchy window and scrolling down to UI, we can select the “Text” option from the menu.
This will create a canvas object, with the text object as a child to it. I renamed my new text as Score_text. In the Inspector window you can change what text is displayed on screen, as well as color and font. You can also lock the UI element to a spot on the screen.
It is very important to change the “UI Scale Mode” setting under “Canvas Scaler” on your Canvas gameobject. You want it to scale with the screen size, not by pixel (this will cause size issues on different platforms or monitors)
Now you can move the Score_Text object around in your scene window until it is sitting where you want. I chose the top right corner.
So we have the UI element, but we need the the Score to update automatically on enemy death. So let’s look at the logic we need to achieve this.
First off, we are going to create a new C# script, I named mine UIManager. Attach this script to the Canvas gameobject in your hierarchy window.
Now we need code the functionality of the system. I started by making a new variable in the UIManager C# script.
Go back to Unity and drag the Score_Text object we made into that new variable component on the Canvas.
We need to make a function that will update our score when called.
We also need to put a value in void Start so that the score will reset to 0 on a new playthrough.
Finally, it is time set the parameters to call the score update function. Seeing as we earn points for destroying enemies, we will put the call on the Enemy.cs script. However, we still need to define what adding the score will look like.
Let’s add a function to our Player.cs (because the Enemy.cs already knows it exists and can interact with it).
The final step is adding the logic to the enemy destroy function on the Enemy C# script.
Now our score will update when a laser collides with an enemy object. If you want to change how much score you get, you can easily do so right here by changing the integer value on the _player.AddScore(X).