Unity3d. How to get the screen or world position of an ui element

I have interface elements (image, etc.). The canvas is attached to the camera. There is a RectTransform , but how to convert this data to the coordinates of the screen or the world and get the center point of this image?

Tried RectTransform.GetWorldCorners but returns null vectors.

+9
source share
3 answers

yourRectTransform.rect.center for the center point in local space.

yourRectTransform.TransformPoint to convert to world space.

It is strange that RectTransform.GetWorldCorners does not work as indicated. You need to call one of the other answers after Awake (so that the layout can happen).

+14
source

You can work with GetWorldCorners , but only when using a child that has real dimensions. I got reasonable values ​​for a child from world space canvas.

+2
source

I found that both GetWorldCorners and TransformPoint only work on Start (), not Awake (), as if we had to wait for the content to resize

  Vector3 min = referenceArea.rectTransform.TransformPoint(referenceArea.rectTransform.rect.min); Vector3 max = referenceArea.rectTransform.TransformPoint(referenceArea.rectTransform.rect.max); elementToResize.transform.localScale = new Vector3(Mathf.Abs(min.x - max.x) , Mathf.Abs(min.y - max.y), 1f); elementToResize.transform.position = referenceArea.rectTransform.TransformPoint(referenceArea.rectTransform.rect.center); 
+2
source

Source: https://habr.com/ru/post/985882/


All Articles