Learning Unity — Taking Unity UI To The Next Level

Joshua Nielsen
3 min readJun 24, 2021

--

In the last article, we took our first look at building user interfaces in Unity. In this article, we’re going to continue working on UIs and seeing how we can use Unity to take them to the next level.

To do that, we are going to fiddle a bit with a UI text element to further explore what is possible. The first thing we’re going to try is to see if user input can work on UI elements the same as they can with game objects. Let’s get started.

To start, we’ll need to create a Text UI element. We will also need a new script, and to apply that script to the new Text element. Within the script, we want to find the Update method, and then add some code that will trigger when the user presses the space key.

For that code, we will use the GetComponent method to access the Text component of the object. And then when we have that component, we will then change the color property to a different color. The code should look something like this:

The Update method has been modified to change the color of the text

If we run the game now, the result will be that pressing the space key results in the text turning from white to red. Here is that result in action:

The text changes color due to user input

So we can see that we can use scripts to manipulate UI elements in the same manner we could manipulate game objects. This allows us to do a lot of really cool stuff with our UI. We could even do some stuff that maybe we wouldn’t even consider doing with a regular game object.

Which brings me to the next example — how we can create a “flashing” effect on our UI elements. Flashing text is a classic element in old arcade games, and we may want to include such an effect in our own projects.

The way we are going to recreate this effect is through coroutines. So in our script we will now create a new coroutine method. It will start by once again using the GetComponent method to access the Text component. Then we will create a loop, and within that loop we will change the text between two different states and wait a small amount of time between those states.

Coroutine to cause the text to “flash”

For the flashing effect we are seeking to create, the two different states of the text will be the text we want to “flash” and no text at all. We can do this by changing the value of the text property.

The script causes the text to “flash”

This is a simple example, but by using these same principles you can make your UI elements do any number of things with some scripting.

That concludes our exploration of the Unity UI system. In the next article, we’re going to learn how to move between Unity scenes while in game. Until then, good luck and happy coding!

--

--

No responses yet