How to create a UI in Unity!
Display Score System and update the UI with code
Create an UI Text
Hierarchy > R-Click > UI > Text
You’ll notice Canvas and Event System is created. All UI elements will be put in Canvas by default. To see it in the Scene view you need to zoom out quite a bit. The Event System needed for interaction with the UI button etc.
Move the create UI element in the Scene view and watch how it’s placed in the Game view.
UI and different screen sizes
Always resize the window and verify the UI is working on different screen sizes. Below you see the text fall off screen.
Adjust the Anchor
This determines from which point of the object the position is calculated.
In this case we set it to the upper right corner so it always is X and Y units away from the upper right corner of the screen.
Adjust UI size based on screen size
In the Hierarchy select: Canvas (Object)
On Canvas Scaler (Script) > UI Scale Mode > Scale with Screen Size
Don’t forget to set the reference resolution.
The Canvas (Component) > Render Mode Screen Space -Overlay — Means it’s always over the game screen)
Score System
Here are the steps to update the game scripts to add a score system when you kill an enemy. Here is the needed logic:
1. Create a score variable
2. When enemy dead add X to score
3. Create method in player to add X to the score
4. Call UIManager script to update score
Update the UI from Script
1. Create UIManager script and add it to the Canvas object
2. Create a score variable in UIManager script
3. To use the UI from script we need to add a code library by adding the following line at the top of the script:
using UnityEngine.UI;
4. Create reference to the Score_Text game gameobject/UI element
[SerializeField] private Text scoreText;
5. Assign it with the Inspector
6. Create public method to Update Score text
public void UpdateUI(int scoreUpdate)
{
_score += scoreUpdate;
_scoreText.text = "Score: " + _score;
}