- Home /
I'm having trouble getting the text in Unity's "text mesh" to change its text at runtime.
public class ShipPropulsion : MonoBehaviour
{
bool onGround = false;
int mph = 90;
void Update()
{
GameObject speedometer = GameObject.Find ("Speedometer");
string readSpeed = speedometer.GetComponent<TextMesh>().text;
readSpeed = mph.ToString();
}
}
I have attempted this a few different ways, and I'm not getting any errors, but I'm also not getting anything else. The value just stays displayed as "50" as I've set it in the inspector. I've tried substituting the int with a string, and still get no change in the display at runtime.
I'm sure it's something simple.
Answer by robertbu · Feb 14, 2014 at 07:19 PM
In need to actually change the object referenced by the TextMesh.text. So instead do:
speedometer.GetComponent<TextMesh>().text = mph.ToString();
Hmm. It worked, but I don't understand why. Shouldn't the way I wrote it have worked? What is the difference between what I wrote and the way you wrote it?
When you set readSpeed to equal the text, it copies the text into the new string variable but readspeed does not refer to the text object
That is, string readSpeed = ...().text;
says to copy the value in ().text and save it to a new string called readSpeed
Then, when you change the value of readSpeed, the original object's .text method is not changed.
In @robertbu's method, he is actually changing the value of the .text parameter.
Now, if you wanted to do it your way, and have a variable point at the textmesh, this would work equally well:
Text$$anonymous$$esh tm = speedometer.GetComponent<Text$$anonymous$$esh>() as Text$$anonymous$$esh;
tm.text = mph.ToString();
@perchik's comments are right on. A diagram.
Your code first sets 'readSpeed' to the old string (orange arrow), then it set it to the new string. Your code does not set Text$$anonymous$$esh.text to the new string. Strings are immutable in C#, so there is no easy way to change the contents of the old string. 'mph.ToString() produces a new string.