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.

Question [SOLVED] Wrong Position of Rect Transform When Trying to Move it Using WorldToScreenPoint

Discussion in 'Scripting' started by ironfiftynine, Mar 27, 2023.

  1. ironfiftynine

    ironfiftynine

    Joined:
    Jan 22, 2013
    Posts:
    61
    Good day. I am having a problem on positioning my Text Mesh Pro Text above a designated object. Please see my video below:



    Notice that the numeric texts are displayed on the left side of the model but what I'm trying to do is place it above the model. Here's the code that I use:

    Code (CSharp):
    1. public Vector2 GetUIPosFromWorldPos(Canvas canvas, Vector3 worldPosition)
    2. {
    3.      // Calculate *screen* position (note, not a canvas/recttransform position)
    4.      Vector2 canvasPos;
    5.      Vector2 screenPoint = Camera.main.WorldToScreenPoint(worldPosition);
    6.  
    7.      RectTransform canvasRect = canvas.GetComponent<RectTransform>();
    8.  
    9.      // Convert screen position to Canvas / RectTransform space <- leave camera null if Screen Space Overlay
    10.      RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRect, screenPoint, null, out canvasPos);
    11.  
    12.  
    13.      return canvasPos;
    14. }
    And the function is used like this:

    Code (CSharp):
    1. // place the text on the specified world position
    2. TMP_Text textInstance = GameObject.Instantiate(this.popupText) as TMP_Text;          
    3.  
    4. textInstance.rectTransform.SetParent(this.popupText.rectTransform.parent, false);
    5. Canvas parentCanvas = textInstance.GetComponentInParent<Canvas>();
    6. textInstance.transform.localPosition = GetUIPosFromWorldPos(parentCanvas, spawnWorldPos);
    I instantiate the textmesh pro text inside a canvas. The properties of the canvas are the following:



    And the properties of the text:



    Any idea on what I did wrong? Thanks in advance.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    33,802

    Your alignment (bottom image) is set to left and top.
     
    ironfiftynine likes this.
  3. ironfiftynine

    ironfiftynine

    Joined:
    Jan 22, 2013
    Posts:
    61
    Thank you so much. I'm facepalming hard right now for not noticing it all this time.
     
    Kurt-Dekker likes this.