The cover for A Beginner's Guide to RectTransforms in Unity

A Beginner's Guide to RectTransforms in Unity

August 30, 2023

Are you a beginner game developer? One of the essential components you’ll encounter is the RectTransform.

A RectTransform is the fundamental Component of UI elements in Unity. What the Transform is for 3D objects, the RectTransform is for UI elements.

As a developer who makes assets for Unity, I use Unity’s UI system to make setting up and changing demo scenes easy.

For example, I use RectTransforms in Unity’s UI system to show settings for the Radial Blur asset.

You must be familiar with the Unity UI system as a game developer.

Understanding how to use RectTransform is crucial. It will help in creating user interfaces and UI animations. It is also helpful in positioning game objects within the Unity canvas. Let’s break down its properties and practical use cases for better understanding.

(By the way, if you’re looking to add UI Gradients in Unity, we have a solution for that.)

What you need to know

  • RectTransform is the fundamental component for creating user interfaces in Unity.
  • RectTransform is the UI equivalent of Transform.
  • When you create a RectTransform, you anchor it to a position on the canvas.
  • The position of the RectTransform is relative to that position.
  • You can also set transformations on the RectTransform, like Rotation and Scaling.

The most essential part of the Unity UI system is the RectTransform component. This component includes a ton of different properties. And the way it works is quite different from the transform component.

It is easy to become confused about what you need to change in the RectTransform to position your UI element correctly.

However, this component is essential to creating user interfaces in Unity. As a game developer, you need to know how to use it.

In this comprehensive guide, I will tell you everything you need to know about RectTransforms.

Key Syntax Info

It is a nightmare to work with RectTransforms via scripting. RectTransforms generate calculated rectangles based on the set properties. These properties depend on the selected anchor preset.

As a result, it is tricky to write reusable code snippets for RectTransforms.

Syntax for RectTransform Position

Use the anchoredPosition property to set or change the position of the RectTransform.

rectTransform = GetComponent<RectTransform>();
rectTransform.anchoredPosition = Vector2.zero;

Syntax for RectTransform Width and Height

Use the sizeDelta property to get and change the width and height.

rectTransform = GetComponent<RectTransform>();
rectTransform.sizeDelta = new Vector2(100, 200);

Syntax for RectTransform Left, Top, Right, and Bottom

Use offsetMin to get and change the Left and Bottom values (when available).

rectTransform = GetComponent<RectTransform>();
rectTransform.offsetMin = new Vector2(500, 650);

Use offsetMax to get and change the Right and Top values (when available).

Note that Unity reports inverted results for the Right and Top values. For example, when Unity shows Top = 10 in the Inspector, the offsetMax.y = -10.

rectTransform = GetComponent<RectTransform>();
rectTransform.offsetMax = new Vector2(500, 650);

What is RectTransform?

RectTransform is the fundamental component of Unity’s UI system. This component is the UI version of the Transform component. As you know, you use the Transform component to set objects’ position, rotation, and scale in your scene. In the same way, you use the RectTransform component to set the position, size, and anchors for UI elements.

In Unity, RectTransform is a fundamental component of the UI system. It is the 2D layout counterpart of the Transform component.

Unity UI Basics

Unity represents every element of the hierarchy as a game object. The UI system is no different. RectTransforms are also game objects.

However, these game objects use the RectTransform component instead of the Transform component. Unity treats a RectTransform as a rectangular container. In contrast, Unity treats a Transform component as an individual point.

Unity UI represents every UI element as a rectangle. UI element children live in those rectangles. The canvas is like a big wrapper around the entire rectangle stack.

I have some analogs to share if you’re familiar with web dev. You can consider the canvas like the <body> HTML tags. And you can think of RectTransform as <div> containers.

Transform represents a single point. RectTransform represents a UI container. It allows you to control the anchor, position, size, and rotation of UI elements within a canvas. It’s essential for creating responsive and dynamic user interfaces.

RectTransform is part of a Canvas. Every RectTransform lives on the canvas.

RectTransform and Hierarchy

You can place a RectTransform into another.

You must parent all RectTransforms to a Canvas component. RectTransforms can be children of other RectTransforms.

Before we dive in, let’s understand the concept of hierarchy in Unity’s UI. Unity lists each UI Element in your scene in the Hierarchy window.

You can drag and drop RectTransform A into RectTransform B in the hierarchy.

When you do this, you make RectTransform A the child of RectTransform B.

At the same time, you are making GameObject B the parent of GameObject A.

  • Key Info:
    A child UI element can have one parent. A parent UI element can have many children. Unity positions a child RectTransform relative to the parent. Unity anchors a child RectTransform relative to the parent element.

We’ll talk more about Anchors later in a dedicated section.

Anatomy of RectTransform

In the next section, we will cover practical aspects. Before that, let’s review the fundamental properties of a RectTransform.

A RectTransform’s available properties change depending on the anchor type.

I generally recommend that you use the Anchor middle/center anchor preset. (All anchor values set to 0.5).

Anchors and Responsive UI

Anchors are crucial for creating responsive UIs in Unity. They define how a UI element should adapt to screen size and resolution changes. Unity represents an Anchor by two normalized values (X and Y). These values range from 0 to 1. The number represents a percentage of the parent canvas’s size.

As the canvas size changes, the element will stay centered. Anchors work in pairs. Adjusting the anchors determines how the component resizes when the canvas changes size.

Position, Width, Height, Left, Right, Top, and Bottom

The position is one of the most fundamental properties of RectTransform. It determines the location of the UI element within its parent canvas. Unity defines the position in pixel units relative to the Canvas scaling type.

For example, assume that your RectTransform uses the Middle/Center anchor. Suppose you set the X and Y positions of a RectTransform to (0, 0). You have positioned your RectTransform to the center of the canvas.

Adjusting the position values will move the element. Controlling the position values is particularly useful when placing UI elements.

The Size property controls the width and height of the UI element. You can define the size in pixels or Unity units. Adjusting the size can make UI elements smaller or larger as needed. For example, let’s say you set the width to 200 and the height to 100. The resulting RectTransform will be 200 pixels wide and 100 pixels tall.

Pivot, Rotation, and Scale

Pivot is the point around which scaling and rotation of the UI element occur. Unity represents the pivot position using normalized values (X and Y). These values are relative to the RectTransform. If you change the pivot, you change how the RectTransform behaves when rotated or scaled.

For instance, suppose that you set the pivot to (0, 0). This pivot value means the scaling and rotation will happen around the element’s bottom-left corner. If you change the pivot to (0.5, 0.5), the RectTransform will scale and rotate around its center.

Rotation allows you to control the angle at which Unity displays the RectTransform. Unity’s rotation value uses degrees. When you rotate a RectTransform, the rotation occurs around the RectTransform’s current pivot. Rotating UI elements can be helpful when you want to create a dynamic interface. For example, you can rotate an image to animate a spinner.

The scale allows you to change the size that the UI element displays. You can scale UI elements from their pivot point. Scaling UI elements can be helpful when you want to make a RectTransform grow or shrink in all directions. You can also scale the RectTransform by a single component direction - x, y, or z. Remember that Unity applies the scaling operation relative to the anchor.

It is best to keep the scale to 1 when setting up your UI in the editor.

FAQs

How do I move RectTransform by script?

In this example, you can use a slider in the Editor with the Lerp method. This method uses the Factor property to move the anchored position of the RectTransform.

using UnityEngine;


[ExecuteAlways, RequireComponent(typeof(RectTransform))\]

public class InterpolateRectTransformPosition : MonoBehaviour

{
  [Range(0f, 1f)]
  public float factor = 1f;
  
  RectTransform rectTransform;
  
  void Start()
  {
    rectTransform = GetComponent<RectTransform>();
  }
  
  void Update()
  {
    rectTransform.anchoredPosition = new Vector2(
      Mathf.Lerp(-200f, 200f, factor),
      rectTransform.anchoredPosition.Y
    );
  }
}

How do I align UI objects?

Let’s say that you have a list of UI objects. In this example, you have centered the UI objects. But you want the UI objects to be left-aligned with one another.

To achieve this, wrap all the UI objects in a parent RectTransform. Then, set the anchor position of the children RectTransforms to Left (Anchors Min.x = 0, Anchors max.x = 0).

How do I hide my Game UI in Scene View?

In the hierarchy, click the eye on the left edge next to the canvas game object.

How do I use Lerp with UI objects?

In this example, you can use a slider in the Editor with the Lerp method. This method uses the Factor property to interpolate the width of the RectTransform.

using UnityEngine;

[ExecuteAlways, RequireComponent(typeof(RectTransform))]
public class InterpolateRectTransformWidth : MonoBehaviour
{
  [Range(0f, 1f)]
  public float factor = 1f;
  
  RectTransform rectTransform;
  
  void Start()
  {
    rectTransform = GetComponent<RectTransform>();
  }
  
  void Update()
  {
    rectTransform.sizeDelta = new Vector2(
      Mathf.Lerp(0f, 500f, factor),
      rectTransform.sizeDelta.Y
    );
  }
}

Learn more about Lerp in my complete guide to using Lerp.

What is a RectTransform anchor?

A RectTransform anchor binds the RectTransform to a particular origin. Remember that this origin is relative to the parent. If you set the anchor as top left, then the position of the RectTransform is relative to the top left of the parent. If the parent moves or rescales in a way that causes the anchor to move, then the RectTransform will also move.

What is a RectTransform pivot?

The RectTransform pivot is the transform origin for the rectangle. When you change the rotation or scale of the object, the pivot sets the basis of that transformation.

What are the most essential properties of RectTransform?

RectTransform includes a ton of different properties. There are only a few that you need to worry about for editor usage:

  • Anchor
  • Position
  • Width and Height,
  • Left, Right, Top, and Bottom

When it comes to runtime API usage, there are four main properties you need to remember:

RectTransform rectTransform = GetComponent<RectTransform>();
Debug.Log(rectTransform.anchoredPosition);
Debug.Log(rectTransform.sizeDelta);
Debug.Log(rectTransform.offsetMin);
Debug.Log(rectTransform.offsetMax);

Add this to your project. Then, adjust the RectTransform’s properties to see how it affects the properties.

How do I define the RectTransform position and size?

Use the position properties to set the position of the RectTransform. Then, use the size properties to set the size. If you listen to me and set the Anchor Position to Middle/Center, you can use sizeDelta. Otherwise, you need to use a combination of sizeDelta, offsetMin, and offsetMax properties.

How do I make the RectTransform adjust to different screen resolutions?

The anchor system enables the RectTransform to adjust to different screen resolutions.

How do I make the RectTransform rotate and scale?

First, set the pivot to where you want the transformation’s origin. Then, set the rotation and scale values.

Here’s how to rotate a rect transform:

RectTransform rectTransform = GetComponent<RectTransform>();
rectTransform.Rotate(10f, 0, 0);

Here’s how to scale a rect transform:

RectTransform rectTransform = GetComponent<RectTransform>();
rectTransform.localScale = rectTransform.localScale * 1.1f;

Do I need to know about Anchor + Anchor Presets?

No. 90% of the time, you should use the Center/Middle Anchor Preset. The anchor preset options are robust. But it can be challenging to wrap your head around how it works.

Do I need to know about Pivot, Rotation, and Scale?

No. 99% of the time, you can ignore pivot + rotation + scale. These tools are potent. If you are new to Unity, learning about all these settings at once can be overwhelming. Pivot, Rotation, and Scale are less critical than Anchors and Positioning. Learn about Anchors and Positioning first.

Try it yourself

Now that we have understood RectTransform better, let’s try applying it. Here is a little task for you. This practice will help you solidify the new information you learned.

Imagine you are making an Android game. You need the UI to look great on all devices. You know that Android devices can be small phones or large tablets. So, you need to create a responsive UI. Your task:

Design your UI

First, design a simple UI for your game. It should include a Health Bar, a Score, and a timer.

Set up the UI

Use Unity’s UI system to make your UI in your scene. Place the UI elements where you think they should go.

Make it Responsive

Now comes the challenge. You aim to make this UI responsive to Android screen sizes and resolutions. Switch between different display resolutions to test your UI in your game view.

Extra Credit

To take it further, add some simple UI animations using RectTransform. For instance, you can make the score scale up when increasing.

Recommended Reading

See how other people solved their problems

Read the Unity manual

Read the Unity UGUI Package Documentation

Conclusion

In this comprehensive guide, I discussed the fundamental concepts of RectTransforms in Unity. I covered the anatomy of RectTransforms, anchors, position, size, pivot, rotation, and scale. I also provided some practical examples of how to use RectTransforms to create user interfaces.

Next, integrate global variables and harness the controlled motion of the MoveTowards methods to add finesse to your toolbox. As a game developer, you must be comfortable using RectTransforms.

Want to build better games?

© 2024