Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

[Fixed] Fetching anchoredPosition of UI component

Discussion in 'Editor & General Support' started by TheLiverMan, Jul 24, 2019.

  1. TheLiverMan

    TheLiverMan

    Joined:
    Aug 17, 2017
    Posts:
    15
    This script is attached to every UI object I need it to.
    Code (CSharp):
    1.  
    2.   public Vector2 tilePosition;
    3.  
    4.   // Start is called before the first frame update
    5.     void Start()
    6.     {
    7.         // CALCULATE TILE POSITION
    8.         CalculateTilePos();
    9.     }
    10.  
    11.     private void CalculateTilePos()
    12.     {
    13.         RectTransform rt = gameObject.GetComponent<RectTransform>();
    14.  
    15.         float x = (rt.anchoredPosition.x);
    16.         float y = (rt.anchoredPosition.y);
    17.  
    18.         // ASSIGN NEW POSITION
    19.         tilePosition = new Vector2(x, y);
    20.     }
    Yet the values of tilePosition are always 0,0. Nothing in any other script modifies tilePosition, so I am confused to what I have done wrong. Here is a screenshot of the gameObject with the script attached.
    upload_2019-7-24_0-55-24.png

    The values I am trying to assign to tilePosition are Pos X and Pos Y of Rect Transform.
     
  2. TheLiverMan

    TheLiverMan

    Joined:
    Aug 17, 2017
    Posts:
    15
    I FOUND THE PROBLEM!

    The problem was that the CalculateTilePos method was being called in Start. I suppose that since each UI object that the Tile script was attached to was being controlled by a grid layout group in a parent object, calling my method would read the values of each individual tile position BEFORE the grid layout group assigned the positions of each object.

    tl;dr: I called my method in the start method. Don't do that if the position is being affected by a grid layout group component
     

    Attached Files:

    Last edited: Jul 25, 2019
    Harrishun likes this.