Find the upper left position of the canvas

To get the position of an object:

Vector3 mainCanvasPosition = mainCanvas.GetComponent<RectTransform>().position;

But it returns the position of the center of the object.

How to get the top left corner position? enter image description here

+4
source share
1 answer

mainCanvas.GetComponent (). rect.xMin gives the minimum position of the canvas in canvas space, and not in world space. Therefore, if you add xMin to the x position of the canvas, you will get the minimum x position of the canvas in world space. And the same goes for y.

So,

float minX = mainCanvas.GetComponent<RectTransform>().position.x + mainCanvas.GetComponent<RectTransform>().rect.xMin;
float maxY = mainCanvas.GetComponent<RectTransform>().position.y + mainCanvas.GetComponent<RectTransform>().rect.yMax;
float z = mainCanvas.GetComponent<RectTransform>().position.z;

Vector3 topLeft = new Vector3(minX, maxY, z);

will provide you the upper left side of the canvas

Edit: https://docs.unity3d.com/ScriptReference/RectTransform-rect.html

Unity, , RectTransform.rect ,

+5

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