How to simply replace text values with variables


With the following method you only have to write the code for replacement once and can change the text in the Editor without digging into the source code again!

  1. Add a new text object:
  2. Create and attach a new script to the text object, something like “ReplaceValueBehavior”:
  3. In the Start() method of ReplaceValueBehavior.cs, set this code (and include UnityEngine.UI for Text):
     var myValue = "world";
     var txtObject = GetComponent<Text> ();
     txtObject.text = string.Format (txtObject.text, myValue);

    Like this:

  4. Now set the text value of the text object to your output string and include a placeholder {0} for your variable:
  5. When the scene starts, the placeholder will be replaced by your value:

Done! 🙂



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s