Search Unity

how to get all lines of text from a textmeshpro inputfield

Discussion in 'Scripting' started by dolfijn3000, Jun 18, 2019.

  1. dolfijn3000

    dolfijn3000

    Joined:
    May 22, 2016
    Posts:
    29
    so im trying to get multiple lines of text from a inputfield.

    here is my code:
    Code (CSharp):
    1.     public GameObject multilineText;
    2.  
    3.     public void LoadPlayersInputField()
    4.     {
    5.  
    6.         TMP_InputField text= multilineText.GetComponent<TMP_InputField>();
    7.         Debug.Log(text.text);
    8.     }
    the problem is that i dont know how to get text from each line. lest say i have 3 names in the input field. how do i get all those names inside a list or array ?
     
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    SparrowGS likes this.
  3. EdGunther

    EdGunther

    Joined:
    Jun 25, 2018
    Posts:
    183
    Would it be bad to make 3 input fields?
     
  4. TheZombieKiller

    TheZombieKiller

    Joined:
    Feb 8, 2013
    Posts:
    266
    You can use TMP_TextInfo.lineInfo to retrieve information about the lines in a text component.

    Code (CSharp):
    1. IEnumerable<string> EnumerateLines(TMP_Text text)
    2. {
    3.     // We use GetTextInfo because .textInfo is not always valid
    4.     foreach (TMP_LineInfo line in text.GetTextInfo(text.text).lineInfo)
    5.         yield return text.text.Substring(line.firstCharacterIndex, line.characterCount);
    6. }
    7.  
    8. // ...
    9.  
    10. foreach (string line in EnumerateLines(inputField.textComponent))
    11. {
    12.     // ...
    13. }
     
  5. ZylaksS

    ZylaksS

    Joined:
    Mar 14, 2018
    Posts:
    18
    Perfect! But I have a question. I have 3 lines in my inputField. If output each line I get 4 outputs and last line is empty. But variable lineCount of TMP_TextInfo storages value of three.
     
  6. TheZombieKiller

    TheZombieKiller

    Joined:
    Feb 8, 2013
    Posts:
    266
    Try this:
    Code (CSharp):
    1. IEnumerable<string> EnumerateLines(TMP_Text text)
    2. {
    3.     // We use GetTextInfo because .textInfo is not always valid
    4.     TMP_TextInfo textInfo = text.GetTextInfo(text.text);
    5.  
    6.     for (int i = 0; i < textInfo.lineCount; i++)
    7.     {
    8.         TMP_LineInfo line = textInfo.lineInfo[i];
    9.         yield return text.text.Substring(line.firstCharacterIndex, line.characterCount);
    10.     }
    11. }
     
    Ale2020 likes this.