UI Elements in Unity
UI, or User Interface, allows us to communicate with the player. In the screenshot below, we use UI to tell the player how many hits they can take, their score and ammo remaining, and the current charge left in their thrusters.
Each of these elements is a game object, and a child of a Canvas object. The thruster bar is particularly complex, consisting of a border, a fill bar, and a background.
Just like any other game object, we can use code to change the properties of the UI elements. We can update the text of the score and ammo to show their current values. When the ammo is 0, we can change the text’s color property to red.
The thruster bar is the most interesting. We change the size of the fill bar based on the amount of thruster time left. When the bar is 66% full or above, we set the color to green. When it’s between 33% and 66%, it’s yellow, and it’s red if below 33%. All of that is done with just a few lines of code!
Every frame, the player object calls this method on the Canvas and tells it what percentage of thruster time is left. It multiples this value by the original width (x value) of the bar image to set it’s size. It then multiplies the percentage by 3 and drops the decimal to get an integer (whole number) from 0 to 2. That number is used to pick the color: 0 = red, 1 = yellow, 2 =green. (The savvy among you will notice the “-0.1” — that’s so the integer can never be 3, even when the percentage is 100.)
This is all good, but so far it’s only one-way communication to the player. But UI elements can also get input from the player. This is evident on the title screen, where clicking the “New Game” UI button, well, starts a new game!