Creating UI in Unity!
Creating UI in Unity is very simple however its capabilities are vast. Unity’s UI system can easily create beautiful user interfaces with highly customizable settings.
To begin, a canvas and event system is needed for UI elements to be displayed and interact with by a user. You can create a canvas in the hierarchy by right clicking. Additionally, you can create a UI element and Unity will automatically generate a canvas and event system.
Within our canvas it's wise to set the UI scale mode to “Scale with Screen Size” rather than “Constant Pixel Size”. This is useful for creating UI systems that work across multiple platforms and devices of different sizes.
Adjusting UI elements through code is very simple, in our case we want a custom Text element to display the player's score. We have a UIManager Game object with a custom script called UIManager. This script will be a hub for managing various elements displayed on the screen.
You can access a text by script when creating a variable of type TextMeshProUGUI. Text mesh pro text contains various additional data useful for creating custom text.
Adjusting UI elements is very similar to managing other components in Unity. For text mesh pro text objects, you can access text with .text.
If text is constantly being adjusted throughout gameplay, a method is created to set text externally. This method can be used in-script and with other scripts since its access modifier is public.
In a different script we can create a variable to reference the UIManager and its methods.
By combining AddScore() and UpdateScore(), every change that occurs to the player score will directly be set in our UI!