Search code examples
c#canvasunity-game-engineposition

Find the upper left position of a 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 can I get the upper left corner position? enter image description here


Solution

  • mainCanvas.GetComponent().rect.xMin gives you minimum x position of canvas in canvas space, not in world space. So if you add xMin to x position of canvas, you get minimum x position of canvas in world space. And same for y.

    So;

    var canvasTransform = mainCanvas.GetComponent<RectTransform>();
    float minX = canvasTransform.position.x + canvasTransform.rect.xMin;
    float maxY = canvasTransform.position.y + canvasTransform.rect.yMax;
    float z = canvasTransform.position.z;
    
    Vector3 topLeft = new Vector3(minX, maxY, z);
    

    will give you top left of canvas

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

    If you look at Unity's reference, you should see that RectTransform.rect is in local space, not in world space