Journal 21 — Adding UI to Unity
The next example I have prepared has to do with the addition of a user interface, or UI. I will show you a scoring system, a lives display, and a game over message overlay.
In Unity, to create some text to show the score in the game, you can right click in the Hierarchy and add Text object. This will automatically create a Canvas and an EventSystem.
Below is a view of the Canvas with the text added for the score, and also a UI image to show the number of lives.
This is how the Canvas looks when overlaid with the Game view.
One important note on the Canvas layout. We want the UI to scale with the screen size, so that the UI will look correct whether you are viewing the game or application on a large display or a phone screen. In the Inspector, we need to update the dropdown selection on the UI Scale Mode.
Below is an example of the UI Scale Mode in action, using the default setting at Constant Pixel Size versus Scale With Screen Size.
To implement the UI text for scoring and the lives images, we need to add the variables below to a new C# script that is attached to the UI Canvas.
With the variables all created in the UIManager script (text variables, image variables), we can drag the objects into the Unity Inspector.
To implement the scoring text, under the Enemy collision checking, we can access a method in the Player script to add points to an integer variable. In this case, we are using a random points per each enemy destroyed instead of a fixed number.
Under the Player script, we will use a local variable to record the score and also a handle to access the UIManager script when we are ready to send the points to update the score text.
In the Player script, we are tracking the player lives, so we can send the lives status to the UIManager script to update the lives onscreen.
In the Player script, we can create a public method to track the score, which is accessed from the Enemy script. As you can see, the method takes in an integer value from the Enemy script. From there, we can send the latest score to the UIManager, which has a method for updating the score in the display.
In the UIManager script, for the game over and restart text, we can set those inactive in the Start method, and activate them later when all the player lives are lost.
In the UIManager, we can create a public method to update the game score. This method is accessed from the Player script.
Similarly, we can create an update method for the player lives that takes the integer data and uses images to show the remaining lives onscreen.
And finally, here are the results with the UI implemented.
Thank you for stopping by!