Unity: How do I get the literal width and height of a RectTransform? Or a UI element?

The Unity UI system is a great thing, but with canvas’s, canvas scalers, child objects with Rect Transforms that also scale and then sizeDelta’s! Things can get a little confusing when trying to figure out the actual size of a UI item like a button.

The solution lies inside the RectTransform, to get the scale of a UI element:

RectTransform rt = myUIGameObject.transform.GetComponent<RectTransform>();
width = rt.sizeDelta.x * rt.localScale.x;
height = rt.sizeDelta.y * rt.localScale.y;
									

Also check the parents of the object. If the object is a direct child of the canvas you’ll be OK, but if it is a child of another object that has a scale then that will affect it (look at  gameObject.transform.parent.localScale). Also I find it best not to have another RectTransform on parent objects – for some reason that makes every scale in the child objects 1!

Remember the root canvas has a scale too. If you have the Canvas Scaler (you probably do), and you find your sizes don’t look like what you expected, just remember the canvas scaler adjusts these.

Please thumb up if this helped you:

[thumbs-rating-buttons]