Search Unity

Dynamic Prefix for an Inputfield and Rect coordinates

Discussion in 'Scripting' started by Micio_del_Cheshire, Sep 28, 2018.

  1. Micio_del_Cheshire

    Micio_del_Cheshire

    Joined:
    Oct 24, 2013
    Posts:
    28
    Hello good sirs!

    I'm trying to create an InputField (TextMesh Pro) with a dynamic (its text content may vary) prefix.
    This spectacular image should explain the goal.

    https://imgur.com/a/qx1eXOa

    So I set a TextMeshPro text to use as Prefix, and by script I was trying to "move" the TextArea accordingly.
    The fact is, TextArea is a RectTransform, and I'm operating in a ScreenSpace render mode.

    I was trying like this:

    Code (CSharp):
    1. private TextMeshProGUI prefix;
    2. private RecTransform textArea;
    3.  
    4.  
    5. public void ChangePrefixTo(string newPrefix)
    6.     {
    7.         float oldWidth = prefix.preferredWidth;
    8.  
    9.         prefix.text = newPrefix;
    10.         float newWidth = prefix.preferredWidth;
    11.  
    12.         Vector2 newPos = new Vector2();
    13.         newPos.x = textArea.position.x + (newWidth - oldWidth);
    14.         newPos.y = textArea.position.y;
    15.  
    16.         textArea.position = newPos;
    17. }
    , but the textArea gets shot into the stars.
    How can I map the RectTransform position according to the size of a TextMeshPro text?

    Thanks for the help and long live the whales
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    You generally want to work with anchors when dealing with UI widgets. Set the TextArea's anchor to be on the left middle side, and then use textArea.anchoredPosition instead of position.
     
  3. Micio_del_Cheshire

    Micio_del_Cheshire

    Joined:
    Oct 24, 2013
    Posts:
    28
    That could be a technical improvement for sure.
    But the issue it's not HOW to move the TextArea but rather HOW MUCH move it.
    I don't know which unit of measurement they are using, but (newWidth - oldWidth) is 88, in my scene, while the number I should add to textArea.position (or AnchoredPosition) should be a bit less than 1.
    I can't figure out how can I map one value into the other, or how can I get more suitable values.