The Graphical User Interface or GUI is a powerful tool that is used when a developer wants to develop plugins and tools for games in Unity.
The contents of this blog are for the intermediate level, and today we will be learning how GUI tools can be used and getting introduced to their features. Let's look at a few GUI elements and learn to create and use them in our project.
Create a script and create an
OnGUI() function in it as shown below.
We use Unity's
OnGUI() method and define our requirements for our GUI Box.
Here we create a GUI Box, but its default value may not be what we need. So we define the
dimension of the box.
And finally, we see a result. But this is just a basic implementation of the GUI box. There are many properties that we can set. More details about them can be found on Unity's documentation page.
Now we will be creating a GUI button and listening to its click. Create a file, paste this function inside it, and attach it to any gameObject.
First, we create a
GUIStyle to define the properties of the buttons.
Then we create
GUIContent to fill in the GUI button.
Finally, we create a button and assign a function when it is clicked.
Now we see the button in-game, and when the button is clicked, the
PrintMessage() function will be called instantly.
GUI Scroll View is the same as the ScrollView we use inside the Canvas, except that GUI ScrollView is created as a GUI element instead. Let's look at the code to create a ScrollView.
In this code, we create a ScrollView by the
GUI.(Rect positionRect, Vector2 scrollPosition, Rect viewRect) function.
Rect positionRect: It defines the actual position and dimension of the ScrollView.
Rect viewRect: It defines the position and dimension of the view inside Scroll View. This view may have dimensions greater or smaller than
viewRecthas a width greater than
positionRect, a horizontal slider will be visible. Otherwise, it will not be displayed, which is true for height.
We can also create a GUIBox to show ScrollView in a more beautiful way. We have defined custom properties for GUIBox using GUIStyle, which includes
boxColor and many more.
Now let's see the output.
So this is how we create a GUI ScrollView.
We have introduced a few GUI elements in this post. In the upcoming post, we will see all three GUI elements properly used.