Search Unity

why i should use .position but not .anchoredPosition when canvas.rendermode is overlay ?

Discussion in 'UGUI & TextMesh Pro' started by ArcherLew, Mar 19, 2018.

  1. ArcherLew

    ArcherLew

    Joined:
    Mar 30, 2016
    Posts:
    14
    I want to place a dynamic UGUI Text at the position of the target 3D GameObject. In hierarcy the UGUI Text is the child of a Canvas , and the RenderMode of the Canvas is set to ScreenSpaceOverlay.


    // "label" is UGUI Text GameObject, "target" is the target 3D GameObject
    RectTransform rectTrans = label.GetComponent<RectTransform>();
    Vector2 pos2d = Camera.main.WorldToScreenPoint(target.transform.position);
    rectTrans.position = pos2d;


    Codes works well.
    My question is why i should use rectTrans.position but not rectTrans.anchoredPosition ?
     
  2. Beks_Omega

    Beks_Omega

    Joined:
    Jun 7, 2017
    Posts:
    72
    So when you have a ScreenSpaceOverlay canvas each pixel is 1 unit by 1 unit in world space (hence why canvases are so huge when you edit them in the scene). So when you're getting the WorldToScreenPoint the returned Vector2 is essentially in Screen Coordinates and World Coordinates at the same time (as long as your canvas is in ScreenSpaceOverlay, this doesn't work in the other Canvas Modes).

    You can see this by placing one object at (0,0,0) (white) and another at (canvasWidth, canvasHeight, 0) (red). The first one is ScreenSpaceOverlay and the second one is ScreenSpaceCamera





    So your pos2d variable is in World Coordinates & Screen Coordinates. rectTrans.position is also in World Coordinates, so setting rectTrans.position = pos2d works. rectTrans.anchoredPosition is not in World Coordinates it is positioned relative to the anchors.

    TL;DR rectTrans.position is in the correct Coordinate System, while rectTrans.anchoredPosition is not.
     
    ArcherLew likes this.
  3. ArcherLew

    ArcherLew

    Joined:
    Mar 30, 2016
    Posts:
    14
    OH , You must spend much time drawing pictures and explaining this to me .
    It's so clear and makes me understand easily , That helps me a lot ! You are too kind !
     
    Beks_Omega likes this.