CodeBlanks Logo Icon CodeBlanks

Rect Transform

Learn UI element position and size with Rect Transform.

What is a Rect Transform?

The UI system counterpart to the 3D world's standard Transform is the RectTransform. Beyond position, it governs the width, height, anchors, and pivot of a 2D bounding rectangle.

// Adjusting RectTransform dimensions via code
RectTransform rect = GetComponent<RectTransform>();
rect.sizeDelta = new Vector2(200f, 50f);

All entities residing beneath a Canvas automatically carry a RectTransform rather than a basic Transform.

Anchor and Pivot logic

Anchors define pin points relative to parent edges to prevent elements drifting off-screen when resolutions shift. Pivot represents the element's local origin for rotation and scaling.

// Centering the pivot point to (0.5, 0.5)
rect.pivot = new Vector2(0.5f, 0.5f);

Proper anchor configuration ensures interfaces scale cleanly across mobile screens and ultrawide desktop monitors alike.

Practice Print Anchor and Pivot info

Assign "TopRight" to anchor and "(0.5, 0.5)" to pivot. Print Anchor: TopRight | Pivot: (0.5, 0.5) to the console.

Starter code

Player.cs
using System;

class Program
{
    static void Main()
    {
        // anchor ve pivot değerlerini tanımlayıp yazdır
    }
}

Sample solution

Player.cs
using System;

class Program
{
    static void Main()
    {
        string anchor = "TopRight";
        string pivot = "(0.5, 0.5)";
        Console.WriteLine("Anchor: " + anchor + " | Pivot: " + pivot);
    }
}

Expected output

Anchor: TopRight | Pivot: (0.5, 0.5)

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which setting locks a UI element to a specific screen corner (e.g. top-left) across different resolutions?

  • AudioListener
  • Anchor Correct answer
  • Lightmap UV
  • MeshCollider

Explanation: The Anchor setting pins a UI element's relative position against parent screen edges or corners.

2 Access RectTransform component

Question
RectTransform rt = GetComponent<____>();
Answer
RectTransform rt = GetComponent<RectTransform>();

Explanation: The RectTransform type is used to access the rectangular dimensions of objects beneath a Canvas.

3 RectTransform terms

Term Meaning
RectTransform Holds UI position and size
Anchor Pins UI to parent corners
Pivot Rotation & scaling origin
sizeDelta RectTransform width & height

All lessons in Intermediate