How to simply replace text values with variables

overview

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:
    1
  2. Create and attach a new script to the text object, something like “ReplaceValueBehavior”:
    2
  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:
    3

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

Done! 🙂

 

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s