Ease of Building UI Elements in Unity With a Score System — Part 01
--
Objective: To show how simple it is to use Unity’s UI features and get a Score System added into our game!
Now that we have a functioning game filled with enemies, lasers, powerups and gorgeous art work, it is time to add some UI features into our 2D Galaxy Shooter and honestly it couldn’t be any easier! I must admit I haven’t played around with the UI much in creating games as I thought it was a whole new beast that would take months to conquer, but let’s just see how easy it really is.
Adding a Score Text UI
To get started, within the Hierarchy window, right click and select UI and a whole bunch of options related to the UI is going to pop up. In this case we are going to use the simple ‘Text”. When this is done, you will see 3 new game objects in the Hierarchy window:
The first is the Canvas which is a component that controls how various UI elements will be rendered and all UI elements must be a child of a canvas, meaning that there must always be a Canvas when adding UI elements. There can also be more than one Canvas in the scene.
Automatically when we added the “Text” UI element to our Hierarchy, a Canvas was created and the “Text” was added as a child of the Canvas.
Let’s go ahead and change our “Text” to a more appropriate name: “Score_Text”.
You will also notice if you look in the Scene view that you have this GIGANTIC box that has been added and the text is huge and not in the right place you want it to be…(Don’t be alarmed, this is very normal and we will play around with some settings shortly to adjust it).
Let’s now change the ‘Score_Text” Colour so we are able to read the text against our dark background. I am going to change it to white:
We are now going to change the following settings on the “Score_Text”:
Firstly, change the name of the text to “Score”. Secondly, let’s make the font a bit bolder so it stands out more by changing this setting to Bold and lastly let’s bump up the size a bit to 20. We will continue to play around with these settings as we go and please feel free to make it look however you want it to look like!
You will now notice in the Game window that we have the new text in the bottom right corner:
I want to now move this to the top right corner of our game and I also want to keep this text anchored to this corner no matter what screen size the game is going to be played on. On the “Score_Text” game object again in the Rect Transform component, click on the square icon and change it to the top right as shown below:
I have also changed the position of the X and Y so that it sits in the corner nicely:
Lastly, on the Canvas game object we want to change the Canvas Scalar component so that it scales with the screen size and also to change the reference resolution for our game to 1920 x 1080.
Next up: Part 02 — Adding scripting to our UI so the Score can be updated in game.