# Question How to get a Rect in screen space from a RectTransform?

Discussion in 'UGUI & TextMesh Pro' started by sildeflask, Sep 11, 2023.

Joined:
Aug 16, 2023
Posts:
201
I have an object with a RectTransform component

I want to get a rect in screen space of that object

so that would be in pixel values

can consider that the object is not out of camera view if needed

Joined:
Aug 16, 2023
Posts:
201
welp

3. ### kidmethuselah

Joined:
Jan 14, 2021
Posts:
16
yet still one of the top posts on googles stupid SEO. yay

Joined:
Aug 16, 2023
Posts:
201
i found out how to do it if you want

not like the mods helped by moving this out of the scripting forum

5. ### kidmethuselah

Joined:
Jan 14, 2021
Posts:
16
Yeah I'd love to know! That's for responding btw

Joined:
Aug 16, 2023
Posts:
201
Code (CSharp):
1.   // Get the corners of the RectTransform in world space
2.         Vector3[] corners = new Vector3[4];
3.         rectran.GetWorldCorners(corners);
4.
5.         // Convert world space to screen space in pixel values and round to integers
6.         for (int i = 0; i < corners.Length; i++)
7.         {
8.             corners[i] = cam.WorldToScreenPoint(corners[i]);
9.             corners[i] = new Vector3(Mathf.RoundToInt(corners[i].x), Mathf.RoundToInt(corners[i].y), corners[i].z);
10.         }
11.
12.         // Calculate the screen space rectangle
13.         float minX = Mathf.Min(corners[0].x, corners[1].x, corners[2].x, corners[3].x);
14.         float minY = Mathf.Min(corners[0].y, corners[1].y, corners[2].y, corners[3].y);
15.         float width = Mathf.Max(corners[0].x, corners[1].x, corners[2].x, corners[3].x) - minX;
16.         float height = Mathf.Max(corners[0].y, corners[1].y, corners[2].y, corners[3].y) - minY;
17.
18.         // Display the screen space rectangle
19.         Rect screenRect = new Rect(minX, minY, width, height);
20.

eggsamurai likes this.

Joined:
Jan 14, 2021
Posts:
16
Thanks man