Get Lines of a UI text

Hi all,

How can I get the lines of Text that is showing in the game, not in the inspector window, as u see in the picture:

myText = GetComponent<Text>();    
string[] lines = myText.text.Split('

');
try{print(lines[0]);}catch{}
try{print(lines[1]);}catch{}

 //real output :
 //New Text
 //What I expect:
 //New
 //Text

Text.cachedTextGenerator has the info you need. It won’t show correct line splitting until the next frame, but you can force it to update early by calling Canvas.ForceUpdateCanvases().

myText.text = "this is a very extremely super duper incredibly unbelievably very long sentence";
Canvas.ForceUpdateCanvases();
for (int i = 0; i < myText.cachedTextGenerator.lines.Count; i++) {
	int startIndex = myText.cachedTextGenerator.lines*.startCharIdx;*
  • int endIndex = (i == myText.cachedTextGenerator.lines.Count - 1) ? myText.text.Length*
  •  : myText.cachedTextGenerator.lines[i + 1].startCharIdx;*
    
  • int length = endIndex - startIndex;*
  • Debug.Log(myText.text.Substring(startIndex, length));*
    }

text = myText.GetComponent();
lines = text.cachedTextGenerator.lineCount;

Did you try this?

A single UIText is replaced by UITexts, one for each character.
In your case, it seems that you need to separate by "
", the basic
idea should be the same.

You need to first get the GameObject that it is associated with. Then you need to get the text component of it. Then once you have the Text component, you can use .text to get/set the text.

To get the Gameobject, you can do something like GameObject.Find(); //can take in a tag or game object name.

Then a .GetComponent(); to get the text component

Then .text.

    // You also need the correct imports, think it's only these two.  
    // Might have a  text one too, cant remember.  You can figure that out
    using UnityEngine;
    using UnityEngine.UI;

    GameObject textGO = GameObject.Find("Text");
    Text textInfo = textGO.GetComponent<Text>();
    string[] lines = textInfo.text.Split('

');
try{print(lines[0]);}catch{}
try{print(lines[1]);}catch{}

For reference:

https://docs.unity3d.com/ScriptReference/UI.Text.html