How can I get screen position of a UI element?
anchoredPosition
is the
position of the pivot of this RectTransform relative to the anchor reference point.
Since RectTransform
inherits from Transform
you can simply use
Vector3 pointToTravel = Camera.main.WorldToScreenPoint(objectRectTransform.position);
in order to get the absolute world position.
The position
you see in the in the Inspector is always the
-
localPosition
forTransform
- relative to the parent GameObject.or
-
anchoredPosition
forRectTransform
depending on the anchor settings - relative to the anchor reference point.
However in the case your Canvas is a Screenspace Overlay
all the contained UI (or better RectTransform
s) already uses the screenspace coordinates in pixels so the WorldToScreenPoint
is unnecessary or better said returns incorrect values.
So in that case you could instead simply use
Vector3 pointToTravel = objectRectTransform.position;
Related videos on Youtube
Roger Tello
Updated on June 04, 2022Comments
-
Roger Tello almost 2 years
I'm trying to get the global position of a UI element.
I've tried so many different ways to get the position but none of them seems to work. The problem comes with the anchors, as i'm moving them and not the UI element position itself (for resolution purposes), the position of the UI showing in the inspector is always 0,0,0. I also tried to get the anchoredPosition and also the Corners to make some calculations but it still not working, I always get (0,0,0) or some incoherent numbers.
Vector3 pointToTravel = Camera.main.WorldToScreenPoint(objectRectTransform.anchoredPosition);
This 'pointToTravel' variable should hold the screen position in pixels of the ui element.