How can I get screen position of a UI element?

11,463

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 for Transform - relative to the parent GameObject.

    or

  • anchoredPosition for RectTransform 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 RectTransforms) 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;
Share:
11,463

Related videos on Youtube

Roger Tello
Author by

Roger Tello

Updated on June 04, 2022

Comments

  • Roger Tello
    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.