[ad_1]
The User Interface (UI) is the medium through which user interacts with the application. A well-defined user interface enables effective interaction between the user and the application. It not only focuses on the aesthetics, but also maximizes accessibility, efficiency, responsiveness of an application.
Unity3D is a powerful game engine that comes with a UI toolkit for developing user interfaces for your games. It makes UI design quite easy where we use the drag and drop mechanism to include the UI elements into the scene.
In this session, we will learn the basic UI elements in Unity3D.
Project setup
Follow the steps to create a sample Unity3D project in your machine.
- Open the UnityHub and Click on New button.
- Select the Unity version (This tutorial is setup with 2019.4.17 version, recommend using 2019+ versions).
- Choose 3D template, provide a project name and the directory path.
- Click the Create button to create a sample project.
Let’s switch the view mode from 3D to 2D before adding UI elements to the scene so as to arrange the UI elements easily in the scene in 2D view.
Let’s move to UI components.
1. Canvas
Canvas is a rectangular area in the scene view. It acts as a container which holds all UI elements as its child gameobjects. If there is no canvas in the scene, it is automatically generated when a new UI element is added.
To add Canvas to the scene, right click on Hierarchy and select UI → Canvas.
Canvas gameobject contains three components — Canvas
, Canvas Scaler
, Graphic Raycaster
. Canvas component has properties that change where and how the Canvas is rendered on the screen. Canvas Scaler
is used to set the scaling and sorting order of UI elements according to various screen sizes.
Render Mode
defines where the canvas is rendered on the screen.
- Screen Space — Overlay
It places UI elements at the top of the screen of the scene. It scales UI elements in the Canvas to the required size as per the screen size. - Screen Space — Camera
It is similar to the Overlay mode, but user has to specify the camera which renders the UI. The change in camera properties such as area of coverage, shape and size will change the way the UI looks on the screen. - World Space
The UI elements are considered as gameObjects in the scene. It is useful to position the UI elements in the 3D space.
2. Panel
Panel acts as a container which defines an area that will stretch to fit its parent RectTransform
dimensions.
To add Panel to the scene, select a gameObject then right click on Hierarchy and select UI → Panel.
You can change the panel color or modify the image from the Inspector. Use Source Image, Color
attributes of the Image component to change the panel background image and color.
3. Text
Text is used to display textual data in the scene. There are three types of text components in Unity — UI Text (default), 3D Text Mesh, and Text Mesh Pro.
To add Text to the scene, right click on Hierarchy and select UI → Text.
Text component properties:
- Text — Defines the text content.
- Font — Defines font type of the text.
- Font Style — Defines the text style as normal (default), bold, italic or bold and italic.
- Font Size — Defines the size of the text.
- Alignment — Defines the alignment of the text as left, right or center.
Let’s have a look at the UI scripting for the text component. Refer the textObject
into the script and assign the desired text as the text attribute value as follows,
textObject.text = “sample text”;
- Create a folder named
Scripts
underAssets
folder. Right click onScripts
folder, select Create → C# Script and name it asTextDemo.cs
. - Add the following code to it.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TextDemo : MonoBehaviour
{
[SerializeField]
Text txtMessage;
// Start is called before the first frame update
void Start()
{
txtMessage.text = "Hello World";
}
// Update is called once per frame
void Update()
{
}
}
- To create an Empty gameObject, right click on Hierarchy then select Create Empty and name it as UI Controller.
- Drag the script into the UI Controller object. Drag or select the text reference in the script on the inspector window.
- Run the application by clicking on the Play button. You can see that the text changed to
“Hello World”
in the console.
4. Input Field
Input Field is a form of editable Text which is used to collect text input from the user. It contains 2 child gameobjects — Placeholder and Text.
- Placeholder is the text that is displayed while empty (“Enter text…”).
- Text is the actual text.
To add Input Field to the scene, right click on Hierarchy and select UI → Input Field.
Input Field component properties:
- Text — Displays Input Field value.
- Interactable — Boolean value, used to enable / disable the input field.
- Content Type — Defines the type of keyboard layout.
- Line Type — Defines the line type. Single line, Multiline submit, Multiline newline are the acceptable values.
- OnValueChanged() — Event invokes when the input field value is changed.
Let’s have a look at the UI scripting for the input field component. Refer the inputField
into the script and assign the desired text as the text attribute value as follows,
inputField.text = “hello world”;
- Create a folder named
Scripts
underAssets
folder. Right click onScripts
folder, select Create → C# Script and name it asInputFieldDemo.cs
. - Add the following code to it.
using UnityEngine;
using UnityEngine.UI;
public class InputFieldDemo : MonoBehaviour
{
[SerializeField]
InputField inputField;
// Start is called before the first frame update
void Start()
{
inputField.text = "Hello World";
}
// Update is called once per frame
void Update()
{
}
public void OnValueChanged() {
Debug.Log("InputField value changed to " + inputField.text);
}
}
- Attach the script into the UI Controller gameObject and provide reference for the input field.
- Select input field and click on + in
OnValueChanged
event trigger. - Refer UI Controller gameObject and the
OnValueChanged()
method from the dropdown.
Click on the Play button to see the Hello World text in the Input Field and get a debug message when any key is pressed.
5. Button
Button is designed to trigger an action when pressed. Every button has an event called OnClick
that triggers when the user clicks on it.
To add Button to the scene, right click on Hierarchy and select UI → Button.
Button component properties:
- Interactable — Boolean value, used to enable / disable the button.
- Transition — Determines the way the control responds to user actions.
- Navigation — Properties that determine the sequence of controls.
- OnClick() —Event invokes when a user clicks on the button.
Let’s create a button to say “Hello world”.
- Create a C# script named
ButtonDemo.cs
in Scripts folder and assign it into the UI Controller object. - Add the following code to it.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ButtonDemo : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void DisplayMessage() {
Debug.Log("Hello World");
}
}
- Assign the custom method
DisplayMessage
in theOnClick
event. Drag UI Controller object into theOnClick
event in the inspector, selectDisplayMessage
method from the dropdown.
- Run the application by clicking on the Play button. You will get Hello World message when you click on the button.
6. Image
Image control is used to display an image in the UI. It is useful for adding images, icons, logos, backgrounds to the scene. It is similar to the Raw Image control but offers more options for animating the image. Image control requires its Texture to be a Sprite, while the Raw Image can accept any Texture.
To add Image to the scene, right click on Hierarchy and select UI → Image or select UI → Raw Image.
Image component properties:
- Source Image — Texture that represents the image to be displayed.
- Color — The color to apply on the image.
- Material — The Material used to render the image.
- Image Type — The means to display image. It accepts values Simple, Sliced, Tiled and Filled.
- Preserve Aspect — Boolean value, ensures the image preserves its aspect ratio.
- Set Native Size — Set the image dimension to the original size of the image.
Provide 2D Sprites in the Source image
property to add an image to the image gameObject.
Organize the project folders before importing assets into the project. Create a folder named Sprites under Assets folder and place all images in it.
Follow the steps to convert those images into a 2D sprite.
- Click on the image in the project window.
- Change the
Texture Type
fromdefault
toSprite (2D and UI)
- Click on Apply button.
7. Slider
Slider control allows user to select a numeric value from a range of values. It helps us to reduce the efforts to input numerical values in our applications.
To add Slider to the scene, right click on Hierarchy and select UI → Slider.
Slider component properties:
- Interactable — Boolean value, used to enable / disable the slider.
- Direction — Defines the direction of the slider value. It accepts values as Left To Right, Right To Left, Bottom To Top and Top To Bottom.
- Min Value —Minimum value of the slider.
- Max Value — Maximum value of the slider.
- Whole Numbers — If true, the slider takes only integer values.
- Value — Returns the current numeric value of the slider.
- OnValueChanged() — Event invokes when the current value of the slider is changed.
Let’s try slider in action.
- Create a C# script named
SliderDemo.cs
in Scripts folder and assign it into the UI Controller object. - Add the following code to it.
using UnityEngine;
using UnityEngine.UI;
public class SliderDemo : MonoBehaviour
{
[SerializeField]
Slider slider;
void Start()
{
Debug.Log("Initial slider value: " + slider.value);
}
void Update()
{
}
public void OnValueChanged() {
Debug.Log("Slider value: " + slider.value);
}
}
- Assign the custom method (
OnValueChanged
) into theOnValueChanged
event. Drag UI Controller object into theOnValueChanged
event in the inspector and selectOnValueChanged
method from the dropdown. - Drag UI Controller object into the
OnValueChanged
event in the inspector and selectOnValueChanged
function from the dropdown.
- Run the application by clicking on the Play button. You can see the float values on slider change in your console.
8. Toggle
Toggle control is a checkbox that allows user to turn an option on or off. It has OnValueChanged
event that responds when the user changes the current value.
Toggle control is useful for,
- Switching an option on or off (play / pause a game).
- Provide an option to accept a legal disclaimer.
- Choosing one from a set of options (a day of the week).
To add Toggle to the scene, right click on Hierarchy and select UI → Toggle.
Toggle component properties:
- Interactable — Boolean value, enable / disable the toggle.
- Is On — If true, set toggle as on initially.
- Transition — The way toggle reacts graphically when its value is changed. It accepts None or Fade as values.
- Graphic — The image used for the checkmark.
- Group — The Toggle Group that the toggle belongs to.
toggleButton.value
— Returns the status of the toggle as true or false.toggle.isOn
— Returns the on / off state of the toggle.
9. Dropdown
Dropdown is a list used to provide a list of options for the user to choose from. It shows the current chosen option as default. You can select a different option by clicking on the dropdown and selecting the option of your choice.
To add Dropdown to the scene, right click on Hierarchy and select UI → Dropdown.
Dropdown component properties:
- Interactable — Boolean value, enable / disable the dropdown.
- Caption Text — Acts as the placeholder for the dropdown.
- Item Text — Text component to hold the text of the item.
- Value — Index of the currently selected option.
- Options — The list of possible options.
- OnValueChanged() — Event invokes when a user clicks one of the options from the dropdown list.
Let’s have a look at the UI scripting for the dropdown component.
- Create a C# script named
DropdownDemo.cs
in Scripts folder and assign it into the UI Controller object. - Add the following code to it.
using UnityEngine;
using UnityEngine.UI;
public class DropdownDemo : MonoBehaviour
{
[SerializeField]
Dropdown dropdown;
void Start()
{
Debug.Log("Starting dropdown value: " + dropdown.options[dropdown.value].text);
}
void Update()
{
}
public void OnValueChanged() {
Debug.Log("Dropdown value: " + dropdown.options[dropdown.value].text);
}
}
- Assign the custom method (
OnValueChanged
) into theOnValueChanged
event. Drag UI Controller object into theOnValueChanged
event in the inspector and selectOnValueChanged
method from the dropdown. - Drag UI Controller object into the
OnValueChanged
event in the inspector and selectOnValueChanged
function from the dropdown. - Run the application by clicking on the Play button. You can see the dropdown values in each option change in the console window.
10. Scroll View
ScrollView displays its contents inside a scrollable frame. It includes child components such as viewport, scrolling content, and optionally one or two scrollbars.
To add Scroll view to the scene, right click on Hierarchy and select UI → Scroll View.
Scroll View component properties:
- Content — Reference of the RectTransform of the UI element to be scrolled.
- Horizontal — Enables horizontal scrolling.
- Vertical — Enables vertical scrolling.
- Viewport — Reference of the viewport RectTransform which is the parent of the content RectTransform.
- Spacing — The space between the scrollbar and the viewport.
To create a sample authentication scene to experience UI elements in a use case, refer to the following link — https://github.com/codemaker2015/unity-ui-interaction-demos.
Thanks for reading this article.
Thanks Gowri M Bhatt for reviewing the content.
If you enjoyed this article, please click on the clap button 👏 and share to help others find it!
The article is also available on Dev.
The full source code for this demo and tutorial can be found here,
Here are some useful links,
New to trading? Try crypto trading bots or copy trading
[ad_2]
Source link