0
\$\begingroup\$

I've come across a strange case in Unity's UI where the width of a RectTransform isn't the same as what is being reported. I have a transform which is 50 by 50 with no scaling, it is a root object of the canvas yet when I use the information that I get from the transform in code to draw from the bottom left edge of the transform to the top right it doesn't reach all the way!

enter image description here enter image description here

Gizmos.color = Color.red;
Vector2 pos = new Vector2(transform.position.x, transform.position.y);
Gizmos.DrawLine(pos - transform.sizeDelta, pos + transform.sizeDelta);

Vector3[] corners = new Vector3[4];
transform.GetWorldCorners(corners);

Gizmos.color = Color.magenta;
Gizmos.DrawLine(corners[3], corners[0]);
Gizmos.DrawLine(corners[0], corners[1]);
Gizmos.DrawLine(corners[1], corners[2]);
Gizmos.DrawLine(corners[2], corners[3]);

The first section should draw a line from the bottom left to the top right according to what the transform reports are the width and height however they don't reach across the entire transform. Using GetWorldCorners the actual corners can be found and drawn around, with that data you can extract that the actual width is 60 (150.2 - 30.2 = 120 / 2 = 60)!

Why? Is this a bug or an I missing something obvious here?

enter image description here

\$\endgroup\$
1
\$\begingroup\$

This is because RectTransform.sizedelta only query the width and height values with no scaling applyed. You most likely have scaling from your canvas or a parent game object. UI Demo with rect scaled Tested in Unity 5.6.1f1

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.