Textmeshpro: setting text to string.empty does not return an empty string
I'm running into a problem where an empty textmeshpro textbox when empty, does not return an empty string. I'm lost as to what's going on.
It even happens when you manually set it to empty.
OutputFolder is a TextMeshProUGui object.
OutputFolder.text = string.Empty;
if (string.IsNullOrEmpty(OutputFolder.text)) {
string errorString = $"Output Folder has Invalid Name! <{OutputFolder.text}>";
Debug.LogError(errorString);
}
else {
Debug.Log(OutputFolder.text);
}
gives the following (not error)
I've verified that setting it to "test" returns "test". So I'm actually setting it properly.
Edit: printing the length of the string (that was set to string.Empty) returns 1.
Answer by IVOF3412 · Jun 07, 2020 at 06:06 PM
I was hitting the same issue and stumbled upon https://stackoverflow.com/questions/52033231/how-to-validate-text-mesh-pro-input-field-text-in-unity
Changed my TMP_Text to my actual input and it worked first time - hope this helps others
Answer by MarcOrion · Oct 21, 2019 at 08:06 AM
I ran into the same issue myself tonight. I took your example of printing the string length and also discovered that an empty string returns a value of 1. I decided to perform one more test and printed the length of a couple strings. As I thought, they were all length + 1, so it seems that a return value of 1 indicates an empty string.
So I changed my condition from if (myText.text == string.Empty)
to if (myText.text.Length <= 1)
. I threw in the < less than just in case... I am still not sure why empty strings have a length of 1, whether this is by design or by limitation... I don't like not fully understanding why something is but, for the time being, at least my conditional check works as expected.
You've probably since solved or worked around your issue, but I thought I would add to the topic with my own findings.
Hopefully we can get a definitive answer as to why it returns length of 1....