Developing interfaces for mobile applications requires a special approach, since interaction with the screen occurs through touches, not mouse clicks. Unity provides a powerful tool UGUI (Unity GUI), which allows you to create adaptive controls that work on any device under management Android. Creating a button is a fundamental skill needed to implement menus, pauses, and interact with game objects.
In this tutorial, we'll go through the process of adding a button to a scene, customizing its appearance, and binding logic. Particular attention will be paid to the settings Canvasas they determine how the interface will scale on the screens of various smartphones and tablets. Proper configuration at this stage will save you from problems with โleftโ elements in the future.
Let's start with a basic understanding of the user interface architecture in the engine. All UI elements must be contained within a special container that handles rendering and input processing. Without this hierarchy, the button simply will not appear or respond to finger presses.
Creating a Canvas and Basic Button
The first step is to create an object Canvas in the scene hierarchy. This is the root object for all UI elements and ensures they display correctly on top of the game world. To add it, right-click in the window Hierarchy, select UI, and then click Canvas. The system will also automatically create an object EventSystemwhich is critical for processing touch input on Android.
After creating the canvas, you need to add the button itself. Right-click again, now on the object Canvas, select UI and then Button - TextMeshPro (or just Button in older versions). A button with a text label inside will appear in the project structure. Please note that using TextMeshPro is preferred over standard Text as it provides better font quality and support for different languages.
By default, a button is created with a placeholder image and the text "Button". You can change the label by selecting the child object Text (TMP) and editing the field Text in the inspector. To change the background color of the button itself, select the parent object Button and find the component Image. Here you can replace the sprite or change the parameter Color to match the design of your application.
Use 9-slice sprites for buttons so that they stretch correctly without distorting the corners when resizing.
Setting Canvas responsiveness for mobile devices
The key point when developing for Android is the configuration of the component Canvas Scaler. Mobile devices have a huge variety of screen resolutions and pixel densities (DPI). If you leave the default settings, the interface may look correct on your PC, but become microscopic or gigantic on the phone.
Select an object Canvas and find the component Canvas Scaler. Change the parameter UI Scale Mode to Scale With Screen Size. This will cause the interface to scale based on the device screen resolution. Next you need to install Reference Resolution. Usually they use the values 1920 ร 1080 or 1080 ร 1920 depending on the orientation of your game. This resolution will be considered the reference.
An important parameter is Match. It determines whether to give priority when scaling: screen width or height. For portrait games (vertical), the value is often set closer to 1 (Height), and for landscape games - closer to 0 (Width). The value 0.5 is a compromise that preserves proportions when changing the screen aspect ratio.
โ ๏ธ Attention: On some devices with camera cutouts or โnotches,โ interface elements may overlap with system areas. Use a component Safe Area or special assets to take into account safe areas of the screen.
Setting up events and binding scripts
The button itself is just a visual element. In order for it to perform actions, you need to configure the event OnClick. Select the button object and look for the component Buttonin the inspector. At the bottom of this component is a list OnClick(). Click on the symbol +to add a new event.
There are two fields in the slot that appears. In the first field (object), drag the script or scene object that contains the desired function. In the second field (function), select the method that should be executed when clicked. For example, if you have a script GameManager with a method StartGame(), select it from the list GameManager โ StartGame.
For more complex logic you can use C# scripts. Create a new script, for example MenuController.cs, and write a public method inside. Make sure the method takes no arguments if you call it directly through the Unity interface. Example code for loading a scene:
using UnityEngine;using UnityEngine.SceneManagement;
public class MenuController : MonoBehaviour
{
public void LoadLevel(string levelName)
{
SceneManager.LoadScene(levelName);
}
}
โ๏ธ Checking the functionality of the button
Visual feedback and button states
The user must understand that the button reacts to his touch. In Unity, this is implemented through the component Image and color settings in the component Button. In the section Color Tint you can set colors for four states: Normal (normal), Highlighted (on hover, relevant for tests on a PC), Pressed (pressed) and Disabled (inactive).
For mobile devices, the most important is the state Pressed. Change its color to a darker shade of the button's base color. This will create a โpressingโ effect when touched with a finger. You can also set the parameter Transition to Sprite Swapif you want to completely change the button image when pressed, using pre-prepared sprites for each state.
Additionally, you can add sound. To do this, in the component Button find the section Audio (some versions require a separate component or script). Assign AudioClip to press. The sound should be short and sweet, confirming the user's action without delay.
Sound lag problem
If the button sound is played with a delay when first pressed, this is due to the loading of the audio engine. Solution: create an empty AudioSource on the stage and play the sound once when the application starts (in the Start method) to cache it.
Optimization for touch control
The size of the button on the smartphone screen is critical. The human finger is much thicker than the mouse cursor, so the controls must be quite large. The minimum recommended pressing area is approximately 48 ร 48 pixels in terms of screen density, but in practice it is better to make buttons at least 80-100 pixels high for comfortable use.
Use the component Layout Element to control the minimum button size. Add this component to the button object and set the value Min Height. This ensures that even when the interface is heavily compressed on a small screen, the button remains clickable. Ignoring this rule often leads to the fact that users cannot access the โExitโ or โPauseโ button.
It is also worth considering the location of the buttons depending on the chirality of the hands. Frequently used buttons (such as "Action" or "Jump" in games) are best placed at the bottom of the screen within reach of your thumb. Less important buttons (settings, store) can be removed in the upper corners or in drop-down menus.
| Parameter | Recommended value | Impact on UX |
|---|---|---|
| Button height | 80 - 120 px | Easy finger pressing |
| Padding | 20 - 40 px | Protection against accidental clicks |
| Contrast | High | Readability on sun |
| Animation time | 0.1 - 0.2 sec | Interface responsiveness |
Typical errors and their solutions
One of the most common problems is the lack of response of the button to pressing on a real device, although everything works in the editor. Most often, the reason lies in the absence of a component Graphic Raycaster on the object Canvas. This component is necessary so that the input system can โseeโ graphical interface elements. Check its presence in the canvas inspector.
Another common mistake is overlapping the button with other objects. In Unity, the drawing order is determined by the order of the objects in the hierarchy (the lower an object is in the list Hierarchy, the higher it is drawn). Make sure your button is above other background images or panels that might be intercepting input.
If the button fires but doesn't visually change color, check the Interactable property in the component Button. It must be enabled. Also make sure that the component Image assigned sprite or color, otherwise the tint color change will not be noticeable.
โ ๏ธ Attention: Unity interfaces may change with the release of new versions of the engine. If you do not find this option in the menu, check the documentation for your specific version of Unity or use the search in the Inspector window.
The presence of the EventSystem component and Graphic Raycaster is a prerequisite for any interactive UI in Unity to work on mobile platforms.
FAQ: Frequently asked questions
Why is the button not pressed on the phone, although it works in the editor?
Most likely, there is no object on the scene EventSystem or the Canvas component has been removed Graphic Raycaster. Also check if the button is covered by another transparent object with an Image component that intercepts touches.
How to make a button round?
Create a circle sprite in a graphics editor and assign it to the field Source Image component Image y buttons. Either use a mask Mask or RectMask2Dto crop the square texture into a circle shape.
Can one button be used for different actions?
Yes, you can add multiple events to the list OnClick. Each new event will be executed sequentially after clicking. You can also change the function dynamically through a script using the method button.onClick.AddListener().
How to change the font on a button?
Select a child object of the button text. In the component Text (TMP) find the field Font Asset. If the font you need is not there, click on the small circle on the right and create a new one Font Asset from your font file (.ttf or .otf).
Why does the text on a button overflow?
This happens if the text is too long for the size of the button. In the text component settings, enable the Auto Size or Best Fitoption so that the font is automatically reduced to fit in the designated area. Also check the settings Overflow.