Ease of Building UI Elements in Unity
Objective: Implement UI components for lives and points.
Now that the game has enemies and working power-ups, the next thing we need to add is some UI components. After all this is a game, what point is there playing without getting some feedback on how you’re doing.
To get started with UI, right-click in the hierarchy, go to UI, then text. When you create this you’re given the text element but also a canvas. The canvas is basically a container for all of your UI elements. It also create an event system. This system is used for UI interaction.
This text element will be used for our score. Rename it Score_text to make it identifiable later. Go to the inspector and change the color to white to make it stand out and increase the font size (20 in this case). Next we’ll position it in the top right corner using the anchor points and position it using the PosX and PosY settings until you’re happy where it is. Using these anchor points will keep the element in that position for using multiple screen sizes or devices.
Doing this will keep the position but it doesn’t scale it for different screen sizes. For this, go to the canvas and in the inspector, change the UI scale mode to Scale with Screen Size.
To change the text within the element, go to the element and in the inspector change the text (Score: 0 for now). This will get changed in code soon.
To get the score updating, create a new C# sharp callled UIManager and attach it to the Canvas. Go to the player script and create a serialized private int for score and create a public method to add to the score.
Open the enemy script and inside the on trigger enter method within the if other tag is laser, call the player add score method before destroying the enemy using a get component call using a global reference instead of wasting resources calling get component on each collision. To do this create a private Player global variable and assign it in the start method, then you can call the same cached instance rather than a new call each time.
Next to pass the score to the Canvas, in the player script, like with the enemy, create a global UIManager variable and assign it in start using the find the GameObject called Canvas and get the component called UIManager.
In the UIManager script, create a serializable private Text called scoreText and assign it in the inspector then in the start method, set a starting text score. To use this you need to add the using UnityEngine.UI namespace. Next create a public method called UpdateScore that takes in a int variable called playerScore which is then assigned to the scoreText.
Finally go back to the player scripts add score method and call the UIManagers UpdateScore method and pass through the score.
In the next post, we will work on a game over scenario.