Is it possible to check tag for certain components and then change Text?

  • So basically I am trying to search for any tags “Name” and get there component type ‘TextMeshProUGUI’ . text field and replace a word in the text with a different word. I need this throughout the game, so when I have a text for example “‘Name’ went to the shop”. It replaces ‘Name’ with the user’s name.

  • I can find the tags, but replacing each text ‘name’ with the user’s name is where I am having trouble.

Example code:

  • I know I am definitely missing something but I am not sure. Any help is much appreciated.

Thanks in advance!

I think you are confusing the tag with the text being displayed. It is also wasteful to do the same search twice. Try something like this:

TextMeshProUGUI nameText = GameObject.FindGameObjectWithTag(“Name”);

if (nameText != null)

{

nameText.text = enterNameVar.text;

Debug.Log(nameText.name + ".text changed to " + enterNameVar.text);

}

Note that you will always be finding the same object each time you execute this code, even after you have changed the text, so you might want to be sure it only gets run once. If you have to, check for a flag to see if you have already changed the name and if it is true don’t do the search any more times.

Something like this at the class level:

bool nameWasChanged = false;

Surround the lines above with:

if (!nameWasChanged)

{

}

And add this line after you change the text:

nameWasChanged = true;

That way you never do the search or change the text more than one time, once you find the object with the tag “Name”.