• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
This post has been wikified, any user with enough reputation can edit it.
avatar image
9
Question by rahulkk · Jul 23, 2015 at 04:03 AM · parentrecttransformparent-childscreenspacelocalspace

Convert RectTransform rect to screen space

I have a RectTransform that is the child of several other RectTransforms. Is there a way for me to convert the child RectTransform's rect property (which is in the local space of the transform) into global screen space (essentially pixel coordinates relative to a corner of the screen)?

Edit: My Canvas is set to Screen Space - Camera and is rendered by the main camera.

Comment
Add comment · Show 2
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image iHaveReturnd · Jul 23, 2015 at 03:55 PM 0
Share

Is this what you are looking for?

http://answers.unity3d.com/questions/826851/how-to-get-screen-position-of-a-recttransform-when.html

avatar image rahulkk · Jul 23, 2015 at 04:26 PM 0
Share

I have looked at that, but it doesn't seem to work. Here is the code I wrote, please let me know if I should change anything. $$anonymous$$y Canvas is set to Screen Space - Camera and is rendered by the main camera. This script is attached to the RectTransform whose rect I need to find in screen coordinates:

 Vector2 screenPos = RectTransformUtility.WorldToScreenPoint(Camera.main, transform.position);
 print(screenPos);

However, while my RectTransform is entirely on screen (its pivot point and anchors are on screen too), the script outputs:

(-116.3, -429.3), which is not what I would expect. $$anonymous$$aybe the RectTransform position isn't correct, but I don't know to fix that.

12 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by al-gco · Apr 04, 2018 at 10:49 PM

None of the answers here worked for me, and it keeps being first in my Google searches, so hopefully this will be helpful to some future similar soul. It works for my use case as far as I've tested it.

The returned Rect is in screen coordinates, which is to say 0,0 is at the top left corner and y+ is down.

     public static Rect RectTransformToScreenSpace(RectTransform transform)
     {
         Vector2 size = Vector2.Scale(transform.rect.size, transform.lossyScale);
 
         float newRectX = transform.position.x + (Screen.width / 2) - (size.x * (1 - transform.pivot.x));
         float newRectY = Mathf.Abs(transform.position.y - (Screen.height / 2)) - (size.y * (1 - transform.pivot.y));
 
         return new Rect(newRectX, newRectY, size.x, size.y);
     }
 
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by Dowen · May 17, 2018 at 07:42 PM

In 2018, What I have used is RectTransformUtility, by Unity Official Support.

 RectTransform yourRectTransform = yourObject.getComponent<RectTransform>();
 Canvas root = yourRectTransform.transform.transform.root.GetComponent<Canvas>();
 Rect rect = RectTransformUtility.PixelAdjustRect(yourRectTransform, root);

That's it.

Be Noticed: The origin is not what you thought (My guess is 0,0 in the center of screen), you might see the negative x and y, but Width and Height are simply correct in Screen Space.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Carocrazy132 · Feb 12, 2019 at 07:05 PM 0
Share

Why are you getting the transform of a transform of a transform? This answer worked less than almost any other answer here for me.

avatar image
0

Answer by Vendrad · Sep 28, 2018 at 08:10 AM

Yet another answer taking pivot points into account. as neither the answer from @Tobias-Pott nor @IVxIV worked for me...

 public static Rect RectTransformToScreenSpace(RectTransform transform)
 {
     Vector2 size = Vector2.Scale(transform.rect.size, transform.lossyScale);
     float x = transform.position.x - (transform.pivot.x * size.x);
     float y = transform.position.y - ((1.0f - transform.pivot.y) * size.y);
     return new Rect(x, y, size.x, size.y);
 }
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by TextusGames · Feb 28, 2019 at 06:42 PM

Screen mode and pivit indipendant. Working solution (c# 7.3)

 /// <summary>
     /// Returns Left to right top to bottom screen position in rectTransform.
     /// </summary>
     /// <returns></returns>
     public static (bool positionIsInRect, Vector2 positionInRect) GetScreenPositionInRect(
         RectTransform rectTransform,
         Vector2 inputScreenPosition)
     {
         // top left corner
         var corners = new Vector3[4];
         rectTransform.GetWorldCorners(corners);
         var topLeft = corners[1];
 
         // rectTransform.position can be in world coordinate and in screen coordinates
         var canvas = rectTransform.GetComponentInParent<Canvas>();
         var topLeftScreen = canvas.renderMode == RenderMode.ScreenSpaceOverlay
             ? topLeft
             : canvas.worldCamera.WorldToScreenPoint(topLeft);
 
         // LeftRight TopBottom possition in
         var positionInRect = new Vector2(
             inputScreenPosition.x - topLeftScreen.x,
             Screen.height - (inputScreenPosition.y + (Screen.height - topLeftScreen.y)));
 
         // if out of rect return null
         if (positionInRect.x < 0 || positionInRect.x >= rectTransform.rect.width) return default;
         if (positionInRect.y < 0 || positionInRect.y >= rectTransform.rect.height) return default;
 
         return (true, positionInRect);
     }

Pity i spent all my day developing such an easy behaviour...

RectTransformUtility.ScreenPointToLocalPointInRectangle() will work too, but without an example i was not able to understand this function :(

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
14

Answer by JohannesMP · May 04, 2019 at 10:22 PM

I wanted to draw a bounding box of some UI elements when in editor, regardless of their orientation.


The easiest way I found that completely handles all cases of nesting, rotation, scaling, anchor offsets, etc. was to use RectTransform.GetWorldCorners and manually compute the Bounds:

 private static Vector3[] WorldCorners = new Vector3[4];
 public static Bounds GetRectTransformBounds(RectTransform transform)
 {
     transform.GetWorldCorners(WorldCorners);
     Bounds bounds = new Bounds(WorldCorners[0], Vector3.zero);
     for(int i = 1; i < 4; ++i)
     {
         bounds.Encapsulate(WorldCorners[i]);
     }
     return bounds;
 }


Since calls that require a Rect typically are defined as existing on the XY plane (such as Gizmos.DrawGUITexture), computing a rect from the bounds is trivial.


Here is an example:

 private static Texture2D MakeTexture(float opacity)
 {
     Texture2D texture = new Texture2D(2, 2, TextureFormat.ARGB32, false, true);
     texture.SetPixel(0, 0, new Color(1, 0, 0, opacity));
     texture.SetPixel(0, 1, new Color(0, 1, 0, opacity));
     texture.SetPixel(1, 0, new Color(0, 0, 1, opacity));
     texture.SetPixel(1, 1, new Color(1, 1, 1, opacity));
     texture.Apply();
     texture.filterMode = FilterMode.Point;
     return texture;
 }
 
 public float opacity = 0.5f;
 private Texture2D tex = null;
 
 private void OnValidate() => tex = MakeTexture(opacity);
 private void Awake() => tex = MakeTexture(opacity);
 
 private void OnDrawGizmos()
 {
     Bounds bounds = GetRectTransformBounds(transform as RectTransform);
     Rect screenRect = new Rect(bounds.min, bounds.size);
     Gizmos.DrawGUITexture(screenRect, tex);
 }


And the result: alt text

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image drew55 · Jul 19, 2020 at 05:27 PM 0
Share

Lovely post, thank you.

  • ‹
  • 1
  • 2
  • 3
  • ›

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

23 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

World Position Of Child Object Shifted After Parenting 1 Answer

Transform.rotation is setting local rotatoin 0 Answers

Convert local point in RectTransform to screen space 2 Answers

Raycast Layermask doesn't ignore no layered Parent? 1 Answer

Child cant apply variables from parent 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges