Easy UI creation in Unity
Yet another useful feature in Unity is the ability to quickly create a user-interface and integrate it into your game. Unity has built-in UI elements that can be simply added to your project and modified in the scene view.
My Space Shooter game needs a UI, so I first need to create a Canvas object. A canvas is what Unity uses to render UI elements on the screen, and all UI components must be children of a canvas object. Here is the canvas in the scene viewer. You can drag objects around this canvas and it will change the position at which they are drawn on the screen.
I only have a button and an image on this canvas, but Unity has several other UI elements to choose from like simple text labels, slider bars, toggle buttons and text input fields.
To interact with the UI in scripts, “using UnityEngine.UI;” must be added to the top of the script. From there, they can be referenced like any other object. Here are some variables for the text and image elements for my game screen.
When the player destroys an enemy, I created a method to update the score and draw it to the screen. I’m using the .text property of the _scoreText object and changing its value so it will change on the screen.
Next up, I’ll be adding some UI elements that remind the player of their failure when they get destroyed.