Display dynamic values in a localized string
Drive a Smart String entry with a local variable from a script.
Read time 2 minutesLast updated 16 hours ago
Drive a Smart String entry with a local variable from a script.
This example builds a score readout that localizes its text and updates its number from gameplay: in English, in German. The collection table entry owns the sentence, while an associated script owns the number. For the format syntax, refer to Smart Strings.
Score: 120Punkte: 120Prerequisites
Before you start, make sure you have the following:
- A table collection. Refer to Get started with localization.
Author the entry
To author a Smart String entry:
- Open Window > Localization > Resource Tables and select the collection.
- Add a key named with the entry type String.
score-display - Enable the key's Smart string toggle from the row's actions menu (⋮).
- Give each locale a value that uses a placeholder named , for example
scorein English.Score: {score}
Because each placeholder has a name, each translation can place it wherever the language needs it.
Update the value from a script
Add a field, register an named in its local variables, and refresh when the value changes:
LocalizedStringIntVariablescorepublic class ScoreDisplay : MonoBehaviour { public LocalizedString scoreText = new(); IntVariable m_Score = new(); void OnEnable() { scoreText.LocalVariables.Add(m_Score, "score"); scoreText.StringChanged += OnStringChanged; } void OnDisable() { scoreText.StringChanged -= OnStringChanged; scoreText.LocalVariables.Remove("score"); } void OnStringChanged(string value) => GetComponent<TextMesh>().text = value; public void AddPoints(int points) { m_Score.Value += points; scoreText.RefreshString(); } }
In the window, set the field to the entry. Each call to updates the variable and calls , which re-raises with the formatted value. A language change re-raises it too, so the readout stays correct after a value change and after a language change.
Inspector
?
scoreTextscore-displayAddPointsRefreshStringStringChangedExtend the example
For more information about how you can configure dynamic text in your application using Smart Strings, refer to the following links:
- Handle pluralization in the entry itself with the plural formatter, so each language picks the right word form from the count.
- Share values across many strings with persistent variables instead of per-reference local variables.
- Pass one-off values as arguments to instead of registering variables.
GetLocalizedString