How do I get the literal width of a RectTransform?

I’m trying to use the the width of a UI object to define the size of future UI objects.
I have read other questions which have given the answer RectTransform.rect.width. This returns a negative value in my case (because of anchoring). Is there a function to get the real / literal width of the object I am looking at or does it need to be calculated based on the anchor positions?


My solution is to use a coroutine to wait until the next frame for when the objects have finished resizing themselves and use RectTransform.sizeDelta.x or RectTransform.rect.width according to need.

rect.width only works if RectTransform.anchorMin.x and RectTransform.anchorMax.x are the same (overlapping). If they are different (i.e., if the object stretches on X when its parent changes width) then rect.width will contain the width of the object relative to its parent width. Since the object is typically smaller than its parent, this value will be negative.

You could try getting the bounds of the game object:

Renderer renderer = obj.GetComponent<Renderer>();
Bounds bounds = renderer.bounds;
float width = bounds.size.x;

but for a UI Panel object, the GetComponent() call returns null, even if the panel has an Image component in it and that image component is enabled.

Alternately, you could try calling RectTransform.GetWorldCorners(). You pass it an array of four Vector3s and you get back the world coordinates of the four corners. You can then subtract X coords to get the width.

Be aware that this stuff only works if the object is in the scene or if the object does not stretch. If your script is attached to a stretchable object that gets dynamically instantiated at run time, you can’t get its dimensions in Start() because it doesn’t have a parent object yet and consequently hasn’t been sized to fit anything (you’ll just get the original width or height of the prefab).

The width and height of a RectTransform can be <= 0 if stretching by width or height is set in the Inspector. The rect and sizeDelta will return values such as:
rect: (x:0.00, y:36.00, width:0.00, height:-72.00)
sizeDelta: (0.0, -72.0)

even after Canvas.ForceUpdateCanvases() and calling a coroutine.

you could use Mathf.abs(float or int); to change negative to positive and keep positive as positive

RectTransform rt
sizeDelta will give Vector2

Size is always relative to anchors does not matter if it comes from RectTransform.rect.width or RectTransform.SizeDelta. Try the “Rect Transform Extended” asset. You can get the size relative to the parent size (ignoring anchors) and other stuff that should come with Unity: