Posted December 13, 2023 by Steven Ren
Text isn't the only thing you can put inside a canvas! Unity has provided us with a variety of UI tools that we can leverage including images, panels, texts, toggles, sliders, buttons, and other goodies!
This is because on the right in the inspector image you can see that I attached the text to the script on the player called "Character" called "Coin Text"
Let's take a closer look at that shall we?
On line 19 I declared a public TextMeshProGUI (which is the text) and called it goldText. Above it on line 17 is where I declared the int variable gold which is the actual gold tracker since our goldText is actually a string, it can't track our gold effectively.
On line 27 is where I add any additional gold that the player gave themselves in the settings via the GameManager. On line 29 is where I change the gold text for the first time from "New Text". You can see me change it to the number of gold that the player has as a string. Then on line 69 I do the same, updating it to the most current count after I increase the gold float count.
The same idea works not only for text, but for all UI elements. Below you can see my pause menu code. With the way I implemented it, it's a panel that's technically always there but not visible to the player. Only when the player presses escape is when it becomes visible and active.
Of course, this only covered non-interactive UI elements so far but this also works for interactive elements like buttons!
Speaking of interactive UI elements like buttons and sliders, they have a special property: the player can interact with them! For buttons, they have a on Click () property in the inspector and sliders have an On Value Changed (Single) property.
That is where you can run any script functions on when the component is interacted with.
For example, this is my main menu.
As you can see, whenever the slider is moved, it runs SetGold which adds gold to the GameManager which sets the gold text initially as shown earlier.
This covers my basic tutorial on UI systems. Here are some links for further and in-depth reading:
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/index.html
https://learn.unity.com/tutorial/ui-components#
https://blog.unity.com/games/ultimate-guide-to-creating-ui-interfaces
Thank you for reading! Feel free to leave a comment below telling me what I missed and what you would like to get a more in-depth coverage on!