Unity: Building a basic UI
UI is important in a lot of games to give precise feedback to the player on where they are in the game. Here’s how to implement a simple UI in Unity.
The first thing to do is add a Canvas to our scene by right-clicking then UI > Canvas.
You will probably need to zoom out in the Scene view but this is what the Canvas looks like. This is our UI layout.
Next we add a Text element as a child of the Canvas (right-click, UI > Text).
On the Text element we need to anchor this to the top-right. This is to stop it disappearing or moving around the screen as the resolution changes.
On the Canvas we need to change ‘UI Scale Mode’ to ‘Scale With Screen Size’. This ensures that the UI elements scale with the screen size as it changes.
Next we create an empty GameObject and call it ‘UIManager’. You could use the Canvas for this, but I prefer a separate manager. We also create a new script called UIManager.
In the Player script we create a variable to hold the player score and to cache the UIManager.
In Start we get the UIManager and assign it to the variable then check for null, just in case.
We create a method to add points to the player score. It requires an int to be passed when called which will allow us to be more creative with scoring later.
The method then updates the player score variable and passes it to the UIManager.
In the Enemy script we can alter the OnTriggerEnter2D so that when the collision is a laser, we can check player isn’t null then call the AddScore method and pass the points.
Finally, in the UIManager script we need to add using UnityEngine.UI. We create a Text variable which we can assign in the Inspector in Unity (I may assign this in Start in future) and a variable to hold the score.
In Start we set the score in the Text to be the starting score which is zero by default.
We create a method to update the Text every time it is called by the Player script.
The end result is that every time we kill an enemy with a laser, we now earn ourselves a nice 10 points and the UI tells us so!