- Home /
Question by
AbandonedCrypt · Feb 22, 2021 at 06:13 AM ·
uicanvaslocalc# tutorialanchor
Get Rect in Screen Space from RectTransform (Screen Space - Camera)
There is a LOAD of threads offering possible solutions to this, however NONE of them work for a screen space - camera canvas mode.
Comment
Best Answer
Answer by AbandonedCrypt · Feb 22, 2021 at 07:04 AM
Since it seems that I wouldn't have gotten an answer anyways, I did some more fiddling and created a working method:
public static Rect RectTransformToScreenSpace(RectTransform transform, Camera cam, bool cutDecimals = false)
{
var worldCorners = new Vector3[4];
var screenCorners = new Vector3[4];
transform.GetWorldCorners(worldCorners);
for (int i = 0; i < 4; i++)
{
screenCorners[i] = cam.WorldToScreenPoint(worldCorners[i]);
if (cutDecimals)
{
screenCorners[i].x = (int)screenCorners[i].x;
screenCorners[i].y = (int)screenCorners[i].y;
}
}
return new Rect(screenCorners[0].x,
screenCorners[0].y,
screenCorners[2].x - screenCorners[0].x,
screenCorners[2].y - screenCorners[0].y);
}
After searching all of unity answers and the forum I was able to find at least 10 different approaches to this issue of which NONE worked for a Screen Space - Camera canvas mode.
From the rect I can get any information I need in screen space which is great because it makes all future calculations a whole lot easier.