Galaxy Shooter 2D — Building UI #10

Displaying information to our players while maintaining style!

As all digital products, there is always a user interface which helps the user understand and communicate with the software or machine. Videogames are no different. We, as developers, need to share information to our players about the avatar’s status, the surroundings, and the game state, and we do it though UI.

Today, I will add two new UI elements: The number of lives through an image, and a Score through text!

Canvas

For our UI elements to exist, we must first create a Canvas, which is the key component that draws them in the screen and can alter their behaviour! You can either create one manually, or create an UI element (a Canvas will be created if there’s none).

A new GameObject called “EventSystem” will handle any calls made to the UI elements. I suggest you leave it as it is.

One slight change we’ll make to our newly generated Canvas is to switch the UI Scale Mode in the Canvas Scaler component from “Constant Pixel Size” to “Scale With Screen Size”. This change will allow the UI to be properly adjusted between different screens and resolutions!

Adding the Lives

I have 4 sprites for the ship lives, ranging from 0 to 3 lives available. I’ll need a script to update the lives and change the sprites in run-time, but for now, I’ll add an image to my Canvas and set it properly.

Adding the Score

We’ll do the exact same process for the score, however, instead of an image, I’ll use Text to do it! (and yes, unfortunately I’ve seen people use images for text. Don’t be that guy…)

The font used is Kenney Pixel Square.

Linking the values

Now, the game needs an intermediary to update each element. For that, I’ve created a script called UIManager that contains a reference to each UI element and methods to update them.

The text has a special text format to always display 6 digits, and the image sprite is changed between the sprites inside the livesSprites array.

I’m using the Singleton pattern to access this script from any other script!
Accessing the UIManager instance inside my Ship script to update the values!
Easy!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store