RectTransform size with scaled-anchor

Hi, all.
How to get With and Height from RectTransform with anchorMin = (0,0) and anchoreMax = (1,1)?

RectTransform.rect says width = 0 and height = 0, but it’s not a true. How to Unity geting actual size of rect?

2 Likes

I think this is what you want ?

No.

SizeDelta is (0,0) too.

I have RectTransform A with (left = 0, top = 0, right = 0, bottom = 0) fields and parent RectTransform B with Width = 100, Height = 100.
And I want get actual Width and Height of rect A.

Getting parent size not a good idea, b/c I have scale and many different anchors on parent!

1 Like

I see what you mean, sizeDelta returns size relative to anchors.

(transform as RectTransform).rect.size seems to return the correct value for me, is that what you tried?

1 Like

Let’s say, I have something like this

And I want get actual size of Image.

Rect.size = (0,0)
RectTransform.SizeDelta = (0,0)
RectTransform.offsetMax/Min = (0.0)
etc…:frowning:

yeah sure, I did the exact same setup and this works :

using UnityEngine;
using System.Collections;

public class RectSizeScript : MonoBehaviour {

    void OnEnable() {
        Debug.Log(gameObject.name + " (transform as RectTransform).rect.size = " + (transform as RectTransform).rect.size);
    }
 
}

3 Likes

ok… I see.

But I have one more options.

I have LayoutGroup with many items inside. And this thing make my pain.
Childrens of LayoutGroup have size on LayoutElement.preferedWith / preferedHeight
And inside that child I have my Image.

Hi! I know this is an old thread, but I found myself stuck with the exact same issue. After a few hours of trial and error, got it to work with:

var realSize = RectTransformUtility.CalculateRectTransformBounds(transform as RectTransform).size;

Hope it saves someone’s life out there :wink:

6 Likes

did you find any solution to this, i m also in same situation

This worked for me after realizing that i was getting the size at the wrong time. I got it while directly spawning a prefab into a Grid Layout Group object as a child. When saved as a prefab its rect size was 0,0. I instead elected to get the size OnEnable and run a coroutine to wait for a frame (waiting for the end of the frame would also work), then get the size.

But if your UI element is not as complicated as mine you could simply just get the width and height of the Grid Layout Group in the parents. GetComponentInParent()

I know this solution wont work for everyone since most are probably not using a layout group, but it worked form me.

1 Like

If you use object.rect.size you can get the exact size of your object.