📅  最后修改于: 2023-12-03 15:05:36.387000             🧑  作者: Mango
TMPro.TextMeshProUGUI
TO STRINGTMPro.TextMeshProUGUI
is a powerful text rendering component in Unity that allows for advanced text formatting and layout options. One of the most frequently used functions of TMPro.TextMeshProUGUI
is ToString()
, which converts the current text content of the component to a string.
public string ToString();
using TMPro;
public class MyTextController : MonoBehaviour
{
private TextMeshProUGUI myTextMeshPro;
private void Start()
{
myTextMeshPro = GetComponent<TextMeshProUGUI>();
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
string currentText = myTextMeshPro.ToString();
Debug.Log(currentText);
}
}
}
In this example, we first get a reference to a TextMeshProUGUI
component attached to a game object, and store it in a private variable. Then, in the update method, we use Input.GetKeyDown(KeyCode.Space)
to detect if the player has pressed the Space key. If so, we call ToString()
method on the TextMeshProUGUI
component and store the result in a string variable currentText
. Finally, we log the currentText
variable using Debug.Log()
.
ToString()
is a convenient method to retrieve the current text content of a TextMeshProUGUI
component, but it does not reflect any changes made to the component's text properties (such as font size, color, or alignment) after the initial text was set. To get an up-to-date snapshot of the component's text properties, you can use TextMeshProUGUI.GetParsedText()
instead.TextMeshProUGUI
component has Rich Text enabled (which allows you to use tags like <b>
or <color>
in the text content), ToString()
will return a string with the rich text tags included. If you want to remove the rich text formatting and get plain text only, you can use TMP_Text.GetPlainText()
instead.