Search code examples
unity-game-enginetransformgrid-layout

Get position of object in Grid Layout


How can I get the actual position of an object in a grid layout? In my current iteration symbolPosition keeps returning 0,0,0.

public void OnPointerClick (PointerEventData eventData)
{
    // Instantiate an object on click and parent to grid
    symbolCharacter = Instantiate(Resources.Load ("Prefabs/Symbols/SymbolImage1")) as GameObject;
    symbolCharacter.transform.SetParent(GameObject.FindGameObjectWithTag("MessagePanel").transform);

    // Set scale of all objects added
    symbolCharacter.transform.localScale = symbolScale;

    // Find position of objects in grid
    symbolPosition = symbolCharacter.transform.position;
    Debug.Log(symbolPosition);
}

Solution

  • The position value wont be updated until the next frame. In order to allow you to make a lot of changes without each one of them causing an entire recalculation of those elements it stores the items that need to be calculated and then updates them at the beginning of the next frame.

    so an option is to use a Coroutine to wait a frame and then get the position

    public void OnPointerClick (PointerEventData eventData)
    {
        // Instantiate an object on click and parent to grid
        symbolCharacter = Instantiate(Resources.Load ("Prefabs/Symbols/SymbolImage1")) as GameObject;
        symbolCharacter.transform.SetParent(GameObject.FindGameObjectWithTag("MessagePanel").transform);
    
        // Set scale of all objects added
        symbolCharacter.transform.localScale = symbolScale;
    
        StartCoroutine(CoWaitForPosition());
    }
    
    IEnumerator CoWaitForPosition()
    {
        yield return new WaitForEndOfFrame();
        // Find position of objects in grid
        symbolPosition = symbolCharacter.transform.position;
        Debug.Log(symbolPosition);
    }