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: Score: 120 in English, Punkte: 120 in German. The collection table entry owns the sentence, while an associated script owns the number. For the format syntax, refer to Smart Strings.
Before you start, make sure you have the following:
To author a Smart String entry:
score-display with the entry type String.score, for example Score: {score} in English.Because each placeholder has a name, each translation can place it wherever the language needs it.
Add a LocalizedString field, register an IntVariable named score in its local variables, and refresh when the value changes:
public 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 Inspector window, set the scoreText field to the score-display entry. Each call to AddPoints updates the variable and calls RefreshString, which re-raises StringChanged 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.
For more information about how you can configure dynamic text in your application using Smart Strings, refer to the following links:
GetLocalizedString instead of registering variables.