Unity Development — UI
We have talked a lot about the player through our Unity Development Journey thus far. Game design and development is about guiding them through an experience that for them is hopefully fun and enjoyable. The most important component when communicating with players is the UI.
UI stands for User Interface. It is visuals on the screen that portray all the information that user needs to know. Some examples of this include health, score, buttons, and other status indicators. How about we add some to our game and take a look at how easy it is.
In the Hierarchy, go to that ‘+’ you normally use to make new objects and scroll down to the UI section. There are a lot of options here, but we are going to start with the basics. Start with a simple ‘Text.’ You’ll notice there is also something called a TextMeshPro. While that adds more control over your text, it is more advanced than we mean to go right now.
We’ll get back to the Text in a second, but first notice what was added to the Hierarchy as soon as you made that Tex object. You should see a ‘Canvas’ and ‘EventSystem.’ These are both very necessary in Unity UI. The Canvas holds all of the UI, while the Event System controls specific interactive UI. The best example of this is the OnClick() event for buttons.
Go to the Canvas Inspector and find the Canvas Scaler. Change the UI Scale Mode to be ‘Scale With Screen Size.’ Then change the width and height match to be 0.5. All of this will allow all of your UI, whether a text or image, to scale accordingly no matter how big or small the screen playing the game. This will save us a lot of hassle.
Back to the Text. You’ll notice when you try to move it around in the Scene view, it won’t exactly line up with the Game view. This is because it has to match up with the Canvas. The Canvas in the Scene view is shown as a white bordered rectangle that matches with the actual screen. Knowing that, you can play around with the text. Change the size, color, font style and anything else you want.
Create an Image in the Canvas now. Just like the Text, you can move this around in the Scene view canvas, and change its attributes. When you add an existing sprite to the Image, you’ll may notice something in the Inspector say “Preserve Aspect Ratio.” Tick this on and it will make sure no matter how much you stretch the image, it will remain true to the original sprite form.
Usually the UI is set up in a corner, so as not to cover the gameplay. When moving UI out of the center there is another key piece that will help your future self. The Rect Transform (the Transform of all UI objects), has an anchor on it. You can use this to anchor in UI to a specific part of the screen. That way, no matter the screen size or shape, they will remain near where they were anchored.
With all these tools and the coding knowledge you’ve gained, adding proper UI to enhance your game should be no problem.