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! 🙂

 

Leave a comment