Search Unity

Cannot get local position of Rect Transform in a Canvas

Discussion in '2D' started by BytePathGames, Oct 24, 2019.

  1. BytePathGames

    BytePathGames

    Joined:
    Jul 8, 2019
    Posts:
    2
    Hi there,

    So I have the following objects in my scene(see the image). The one we are interested in is the Matrix Gameobject which contains 4x4 tiles. Each tile has is aligned to the left-top corner and given a xy position relative to the Matrix parent.

    The problem I have is I cannot find the local position of each tile. What I am missing?
    Code (CSharp):
    1.  
    2. var tileX0Y0 = (RectTransform) matrixBox.transform.GetChild(12);
    3.  
    4. Debug.Log("position: " + tileX0Y0.name + " " + tileX0Y0.position.x + " " + tileX0Y0.position.y);
    5. // Tile (12) 172.5 472.5
    6.        
    7. Debug.Log("transform.position: " + tileX0Y0.name + " " + tileX0Y0.transform.position.x + " " + tileX0Y0.transform.position.y);
    8. // Tile (12) 172.5 472.5
    9. Debug.Log("ransform.localPosition: " + tileX0Y0.name + " " + tileX0Y0.transform.localPosition.x + " " + tileX0Y0.transform.localPosition.y);
    10. //Tile (12) -367.5 -367.5
    11.        
    12. Debug.Log("position: " + tileX0Y0.name + " " + tileX0Y0.position.x + " " + tileX0Y0.position.y);
    13. //Tile (12) 172.5 472.5
    14. Debug.Log("localPosition: " + tileX0Y0.name + " " + tileX0Y0.localPosition.x + " " + tileX0Y0.localPosition.y);
    15. //Tile (12) -367.5 -367.5
    16.            
    17. Debug.Log("rect: " + tileX0Y0.name + " " + tileX0Y0.rect.x + " " + tileX0Y0.rect.y);
    18. //Tile (12) -112.5 -112.5
    19. Debug.Log("rect.position: " + tileX0Y0.name + " " + tileX0Y0.rect.position.x + " " + tileX0Y0.rect.position.y);
    20. //Tile (12) -112.5 -112.5
    21.  
    None of the Logs will output x: 112.5 y: -847.5 which is the position of the 12 tile relative to it's parent.

    To better understand what I am trying to achieve. I decided to build a 2048 clone but to scale it on as many resolutions as possible I started to build the game only with UI objects. I don't know if it's a good idea or not :) .
    So I have the Matrix container(1000width x 1000 height) and I just want to generate the tiles(225x225) with a spacing of 20 which I am still trying to figure out how as well.

    P.S. Also new to Unity so please explain it as for newbs :D

    Thx,
    Robert

    upload_2019-10-24_13-2-14.png
     
  2. BytePathGames

    BytePathGames

    Joined:
    Jul 8, 2019
    Posts:
    2
    Totally missed transform.anchoredPosition .That's the one :D
     
    mechane and vakabaka like this.