0
0
Unityframework~5 mins

Anchoring and responsive UI in Unity

Choose your learning style9 modes available
Introduction

Anchoring helps UI elements stay in the right place when the screen size changes. It makes your app look good on all devices.

You want buttons to stay at the bottom corners on any screen size.
You need a score display to stay at the top center no matter the device.
You want images to resize or move correctly when the window changes size.
You want text to stay readable and well placed on phones and tablets.
Syntax
Unity
RectTransform.anchorMin = new Vector2(xMin, yMin);
RectTransform.anchorMax = new Vector2(xMax, yMax);
anchorMin and anchorMax define the rectangle's anchors relative to the parent, values from 0 to 1.
Setting both anchors to the same point fixes the UI element to that spot; different values stretch it.
Examples
Anchors set to bottom-left corner. The UI element stays fixed there.
Unity
rectTransform.anchorMin = new Vector2(0, 0);
rectTransform.anchorMax = new Vector2(0, 0);
Anchors set to top center. The UI element stays at the top center.
Unity
rectTransform.anchorMin = new Vector2(0.5f, 1);
rectTransform.anchorMax = new Vector2(0.5f, 1);
Anchors stretch the UI element to fill the parent area.
Unity
rectTransform.anchorMin = new Vector2(0, 0);
rectTransform.anchorMax = new Vector2(1, 1);
Sample Program

This script anchors a UI button to the bottom right corner of its parent canvas. It stays 20 units away from the edges even if the screen size changes.

Unity
using UnityEngine;
using UnityEngine.UI;

public class ResponsiveUIButton : MonoBehaviour
{
    public RectTransform buttonRect;

    void Start()
    {
        // Anchor button to bottom right corner
        buttonRect.anchorMin = new Vector2(1, 0);
        buttonRect.anchorMax = new Vector2(1, 0);
        buttonRect.pivot = new Vector2(1, 0);

        // Set position 20 units from bottom and right edges
        buttonRect.anchoredPosition = new Vector2(-20, 20);
    }
}
OutputSuccess
Important Notes

Always set the pivot point to control how the UI element moves relative to its anchors.

Use the Canvas Scaler component to help UI scale nicely on different screen sizes.

Test your UI on different screen resolutions using Unity's Game view to see how anchoring works.

Summary

Anchors fix UI elements relative to their parent, helping with responsive layouts.

Use anchorMin and anchorMax to set where the element stays or stretches.

Combine anchors with pivot and anchoredPosition for precise control.