Class LocalizedString
Provides a way to reference a StringTableEntry inside of a specific StringTable and request the localized string.
Inherited Members
Namespace: UnityEngine.Localization
Syntax
[Serializable]
public class LocalizedString : LocalizedReference, ISerializationCallbackReceiver, IVariableGroup, IDictionary<string, IVariable>, ICollection<KeyValuePair<string, IVariable>>, IEnumerable<KeyValuePair<string, IVariable>>, IEnumerable, IVariableValueChanged, IVariable, IDisposable
Examples
This example shows how to localize a MonoBehaviour so that it updates automatically when the active locale changes. This example uses asynchronous loading to load the localized assets in the background.
public class ExampleMonoBehaviour1 : MonoBehaviour
{
public LocalizedString myLocalizedString = new LocalizedString("My Table", "My Entry");
public string TranslatedValue { get; private set; }
void Start()
{
// Register to get an update when the string is changed.
myLocalizedString.StringChanged += ValueChanged;
}
void ValueChanged(string value)
{
TranslatedValue = value;
Debug.Log("Value changed to: " + value);
}
}
This example shows how to localize a MonoBehaviour immediately. This example uses synchronous loading, which may cause a pause when first loading the localized assets.
public class ExampleMonoBehaviour2 : MonoBehaviour
{
public LocalizedString myLocalizedString = new LocalizedString("My Table", "My Entry");
public string TranslatedValue => myLocalizedString.GetLocalizedString();
void OnGUI()
{
GUILayout.Label(TranslatedValue);
}
}
This example shows how to localize a ScriptableObject to represent a quest in a game.
[CreateAssetMenu()]
public class GameQuest : ScriptableObject
{
[SerializeField] LocalizedString questTitle = new LocalizedString("My Quests", "QUEST_1_TITLE");
[SerializeField] LocalizedString questDescription = new LocalizedString("My Quests", "QUEST_1_DESCRIPTION");
[SerializeField] LocalizedString success = new LocalizedString("My Quests", "QUEST_1_SUCCESS");
[SerializeField] LocalizedString failure = new LocalizedString("My Quests", "QUEST_1_FAILURE");
[SerializeField] float rewardMoney = 100;
public string Title => questTitle.GetLocalizedString();
public string Description => questDescription.GetLocalizedString();
public string Failure => failure.GetLocalizedString();
// Return the success message with the reward money included.
// For example:
// "Congratulations, you saved the village! Please take this reward of {0:C} as a sign of appreciation"
// in English(GB) would become
// "Congratulations, you saved the village! Please take this reward of £100 as a sign of appreciation"
public string Success => success.GetLocalizedString(rewardMoney);
}
This example shows how to use local variables to represent a health counter.
public class HealthCounterExample : MonoBehaviour
{
public Text uiText;
public float delay = 5;
// Some example English strings could be:
// "{player-name} has {player-health} health"
// "{player-name} {player-health:cond:<100?has {} remaing health|is at full health}"
public LocalizedString myLocalizedString = new LocalizedString("My Table", "My Entry")
{
{ "player-name", new StringVariable { Value = "Player 1" } },
{ "player-health", new IntVariable { Value = 100 } }
};
IEnumerator Start()
{
// Register to get an update when the string is changed.
// This will be called every time the playerHealth variable is modified.
myLocalizedString.StringChanged += val => uiText.text = val;
var playerHealth = myLocalizedString["player-health"] as IntVariable;
var wait = new WaitForSeconds(delay);
while (playerHealth.Value > 0)
{
yield return wait;
// Changing the value triggers the LocalizedString to update itself.
playerHealth.Value -= Random.Range(1, 10);
}
}
}
Constructors
LocalizedString()
Initializes and returns an empty instance of a LocalizedString.
Declaration
public LocalizedString()
LocalizedString(TableReference, TableEntryReference)
Initializes and returns an instance of a LocalizedString.
Declaration
public LocalizedString(TableReference tableReference, TableEntryReference entryReference)
Parameters
Type | Name | Description |
---|---|---|
TableReference | tableReference | Reference to the String Table Collection. This can either be the name of the collection as a string or the Collection Guid as a System.Guid. |
TableEntryReference | entryReference | Reference to the String Table Collection entry. This can either be the name of the Key as a string or the long Key Id. |
Examples
This example shows the different ways to construct a LocalizedString.
public LocalizedString usingNames = new LocalizedString("My String Table", "My Game Text");
public LocalizedString usingTableNameAndEntryId = new LocalizedString("My String Table", 4324324541);
public LocalizedString usingTableGuidAndEntryId = new LocalizedString(new System.Guid("6e79ded14bc9e0a4d9bf2b8aac246bfe"), 323453434);
public LocalizedString usingTableGuidAndEntryName = new LocalizedString(new System.Guid("6e79ded14bc9e0a4d9bf2b8aac246bfe"), "Start Game");
public LocalizedString withLocalVariables = new LocalizedString("My String Table", "My Game Text")
{
// These variables will be visible in the inspector Local Variables field.
{ "some-text", new StringVariable { Value = "Hello World" } },
{ "score", new IntVariable { Value = 100 } },
{ "player-health", new FloatVariable { Value = 0.5f } },
{ "object-reference", new ObjectVariable()}, // Set via the inspector
};
public LocalizedString withNestedTranslation = new LocalizedString("My String Table", "My Game Text")
{
{ "some-text", new StringVariable { Value = "Hello World" } },
{ "nested", new LocalizedString("My String Table", "My Nested Text")
{
{ "score", new IntVariable { Value = 100 } },
}}
};
This example shows how a LocalizedString could be set up in the Editor. By using the Guid and Id the table and entry references will not be lost if the table collection name or entry name was to be changed. Note: The performance benefits to using a Guid and Id are negligible.
public LocalizedString GenerateLocalizedStringInEditor()
{
// The main advantage to using a table Guid and entry Id is that references will not be lost when changes are made to the Table name or Entry name.
var collection = LocalizationEditorSettings.GetStringTableCollection("My String Table");
var entry = collection.SharedData.GetEntry("Start Game");
return new LocalizedString(collection.SharedData.TableCollectionNameGuid, entry.Id);
}
Properties
Arguments
Arguments that will be passed through to Smart Format. These arguments are not serialized and will need to be set at runtime. See Add(String, IVariable) to add persistent serialized arguments.
Declaration
public IList<object> Arguments { get; set; }
Property Value
Type | Description |
---|---|
IList<Object> |
Count
Returns the number of local variables inside this localized string.
Declaration
public int Count { get; }
Property Value
Type | Description |
---|---|
Int32 |
CurrentLoadingOperationHandle
The current loading operation for the string when using StringChanged or default if one is not available. A string may not be immediately available, such as when loading the StringTable asset, so all string operations are wrapped with an AsyncOperationHandle. See also RefreshString()
Declaration
public AsyncOperationHandle<LocalizedDatabase<StringTable, StringTableEntry>.TableEntryResult> CurrentLoadingOperationHandle { get; }
Property Value
Type | Description |
---|---|
AsyncOperationHandle<LocalizedDatabase.TableEntryResult<>> |
HasChangeHandler
Returns true if StringChanged has any subscribers.
Declaration
public bool HasChangeHandler { get; }
Property Value
Type | Description |
---|---|
Boolean |
IsReadOnly
Implemented as part of the IDictionary interface but not actually used. Will always return false.
Declaration
public bool IsReadOnly { get; }
Property Value
Type | Description |
---|---|
Boolean |
Item[String]
Gets or sets the IVariable with the specified name.
Declaration
public IVariable this[string name] { get; set; }
Parameters
Type | Name | Description |
---|---|---|
String | name | The name of the variable. |
Property Value
Type | Description |
---|---|
IVariable | The found variable. |
Examples
This example shows how to get and add a local variable.
var localizedString = new LocalizedString("My Table", "My Entry");
// An example of a Smart String using the variable would be: "You have {player-money:C}.".
// :C will apply the current Locale currency and number formatting.
localizedString.Add("player-money", new FloatVariable { Value = 100.45f });
// Get a variable from the localized string
var variable = localizedString["player-money"] as FloatVariable;
Debug.Log("The value is " + variable);
Exceptions
Type | Condition |
---|---|
KeyNotFoundException | Thrown if a variable with the specified name does not exist. |
Keys
Returns a collection containing all the unique local variable names.
Declaration
public ICollection<string> Keys { get; }
Property Value
Type | Description |
---|---|
ICollection<String> |
Values
Returns all the local variables for this localized string.
Declaration
public ICollection<IVariable> Values { get; }
Property Value
Type | Description |
---|---|
ICollection<IVariable> |
Methods
Add(KeyValuePair<String, IVariable>)
Declaration
public void Add(KeyValuePair<string, IVariable> item)
Parameters
Type | Name | Description |
---|---|---|
KeyValuePair<String, IVariable> | item | The local variable name and value to add. |
Add(String, IVariable)
Adds a new Local Variable to use during formatting.
Declaration
public void Add(string name, IVariable variable)
Parameters
Type | Name | Description |
---|---|---|
String | name | The name of the variable, must be unique. Note the name should not contain any whitespace, if any is found then it will be replaced with with '-'. |
IVariable | variable | The variable to use when formatting. See also BoolVariable, FloatVariable, IntVariable, StringVariable, ObjectVariable. |
Examples
This example shows how to get and add a local variable.
var localizedString = new LocalizedString("My Table", "My Entry");
// An example of a Smart String using the variable would be: "You have {player-money:C}.".
// :C will apply the current Locale currency and number formatting.
localizedString.Add("player-money", new FloatVariable { Value = 100.45f });
// Get a variable from the localized string
var variable = localizedString["player-money"] as FloatVariable;
Debug.Log("The value is " + variable);
Exceptions
Type | Condition |
---|---|
ArgumentException | Thrown when |
ArgumentNullException | Thrown when variable is null. |
Clear()
Removes all local variables.
Declaration
public void Clear()
Contains(KeyValuePair<String, IVariable>)
Declaration
public bool Contains(KeyValuePair<string, IVariable> item)
Parameters
Type | Name | Description |
---|---|---|
KeyValuePair<String, IVariable> | item | The item to check for. Both the Key and Value must match. |
Returns
Type | Description |
---|---|
Boolean | true if a matching variable could be found or false if one could not. |
ContainsKey(String)
Returns true if a local variable with the specified name exists.
Declaration
public bool ContainsKey(string name)
Parameters
Type | Name | Description |
---|---|---|
String | name | The variable name to check for. |
Returns
Type | Description |
---|---|
Boolean | true if a matching variable could be found or false if one could not. |
CopyTo(KeyValuePair<String, IVariable>[], Int32)
Copies the local variables into an array starting at arrayIndex
.
Declaration
public void CopyTo(KeyValuePair<string, IVariable>[] array, int arrayIndex)
Parameters
Type | Name | Description |
---|---|---|
KeyValuePair<String, IVariable>[] | array | The array to copy the local variables into. |
Int32 | arrayIndex | The index to start copying the items into. |
Exceptions
Type | Condition |
---|---|
ArgumentNullException | Thrown when the array is null. |
ForceUpdate()
Declaration
protected override void ForceUpdate()
Overrides
GetEnumerator()
Returns an enumerator for all local variables in this localized string.
Declaration
public IEnumerator GetEnumerator()
Returns
Type | Description |
---|---|
IEnumerator | The enumerator that can be used to iterate through all the local variables. |
GetLocalizedString()
Provides a translated string from a StringTable with the TableReference and the translated string that matches TableEntryReference. Uses WaitForCompletion to force the loading to complete synchronously. Please note that WaitForCompletion is not supported on WebGL.
Declaration
public string GetLocalizedString()
Returns
Type | Description |
---|---|
String | The localized string for the SelectedLocale or LocaleOverride if it is not null. |
GetLocalizedString(IList<Object>)
Provides a translated string from a StringTable with the TableReference and the translated string that matches TableEntryReference.
Declaration
public string GetLocalizedString(IList<object> arguments)
Parameters
Type | Name | Description |
---|---|---|
IList<Object> | arguments | The arguments to pass into the Smart String formatter or String.Format. |
Returns
Type | Description |
---|---|
String | The localized string for the SelectedLocale or LocaleOverride if it is not null. |
GetLocalizedString(Object[])
Provides a translated string from a StringTable with the TableReference and the translated string that matches TableEntryReference. Uses WaitForCompletion to force the loading to complete synchronously. Please note that WaitForCompletion is not supported on WebGL.
Declaration
public string GetLocalizedString(params object[] arguments)
Parameters
Type | Name | Description |
---|---|---|
Object[] | arguments | The arguments to pass into the Smart String formatter or String.Format. |
Returns
Type | Description |
---|---|
String | The localized string for the SelectedLocale or LocaleOverride if it is not null. |
GetLocalizedStringAsync()
Provides a translated string from a StringTable with the TableReference and the translated string that matches TableEntryReference.
Declaration
public AsyncOperationHandle<string> GetLocalizedStringAsync()
Returns
Type | Description |
---|---|
AsyncOperationHandle<String> | Returns the loading operation for the request. |
Remarks
The Completed event provides a notification once the operation has finished and the string has been found or an error has occurred. A string table may have already been loaded during a previous operation or when using Preload mode. Check the IsDone property to see if the string table has already been loaded and the translated string is immediately available. See Async operation handling for further details. To force the operation to complete immediately, call WaitForCompletion().
Examples
This example shows how GetLocalizedStringAsync() can be used to request an updated string when the SelectedLocale changes.
public class LocalizedStringGetExample : MonoBehaviour
{
public Text myText;
public LocalizedString myString = new LocalizedString
{
TableReference = "My String Table",
TableEntryReference = "My Game Text"
};
void OnEnable()
{
LocalizationSettings.SelectedLocaleChanged += LocaleChanged;
LoadString();
}
void OnDisable()
{
LocalizationSettings.SelectedLocaleChanged -= LocaleChanged;
}
void LocaleChanged(Locale locale)
{
LoadString();
}
void LoadString()
{
var operation = myString.GetLocalizedStringAsync();
UpdateString(operation);
}
void UpdateString(AsyncOperationHandle<string> value)
{
if (!value.IsDone)
{
// Defer the callback until the operation is finished
value.Completed += UpdateString;
return;
}
myText.text = value.Result;
}
}
This example shows how GetLocalizedStringAsync() can be forced to complete immediately using WaitForCompletion().
public class LocalizedStringSynchronousGetExample : MonoBehaviour
{
public Text myText;
public LocalizedString myString = new LocalizedString
{
TableReference = "My String Table",
TableEntryReference = "My Game Text"
};
void OnEnable()
{
LocalizationSettings.SelectedLocaleChanged += LocaleChanged;
LoadString();
}
void OnDisable()
{
LocalizationSettings.SelectedLocaleChanged -= LocaleChanged;
}
void LocaleChanged(Locale locale)
{
LoadString();
}
void LoadString()
{
var operation = myString.GetLocalizedStringAsync();
operation.WaitForCompletion(); // Force synchronous loading
myText.text = operation.Result;
}
}
GetLocalizedStringAsync(IList<Object>)
Provides a translated string from a StringTable with the TableReference and the translated string that matches TableEntryReference.
Declaration
public AsyncOperationHandle<string> GetLocalizedStringAsync(IList<object> arguments)
Parameters
Type | Name | Description |
---|---|---|
IList<Object> | arguments | The arguments to pass into the Smart String formatter or String.Format. |
Returns
Type | Description |
---|---|
AsyncOperationHandle<String> | Returns the loading operation for the request. |
GetLocalizedStringAsync(Object[])
Provides a translated string from a StringTable with the TableReference and the translated string that matches TableEntryReference.
Declaration
public AsyncOperationHandle<string> GetLocalizedStringAsync(params object[] arguments)
Parameters
Type | Name | Description |
---|---|---|
Object[] | arguments | The arguments to pass into the Smart String formatter or String.Format. |
Returns
Type | Description |
---|---|
AsyncOperationHandle<String> | Returns the loading operation for the request. |
GetSourceValue(ISelectorInfo)
The value that will be used when the smart string matches this variable. This value can then be further used by additional sources/formatters.
Declaration
public object GetSourceValue(ISelectorInfo selector)
Parameters
Type | Name | Description |
---|---|---|
ISelectorInfo | selector | The details about the current format operation. |
Returns
Type | Description |
---|---|
Object |
Implements
RefreshString()
Provides a way to force a refresh of the string when using StringChanged.
Declaration
public bool RefreshString()
Returns
Type | Description |
---|---|
Boolean | Returns true if a new refresh could be requested or false if it could not, such as when CurrentLoadingOperationHandle is still loading. |
Remarks
This will only force the refresh if there is currently no active CurrentLoadingOperationHandle, if one is still being executed then it will be ignored and false will be returned. If a string is not static and will change during game play, such as when using format arguments, then this can be used to force the string to update itself.
You may wish to call this if the values inside of the Arguments list have changed or you wish to force all StringChanged subscribers to update.Examples
This example shows how the string can be refreshed, such as when showing dynamic values like the current time.
/// <summary>
/// This example expects a Smart String with a named placeholder of `TimeNow`, such as "The time now is {TimeNow}".
/// </summary>
public class LocalizedStringSmart : MonoBehaviour
{
public LocalizedString myString;
string localizedText;
public float TimeNow => Time.time;
/// <summary>
/// Register a ChangeHandler. This is called whenever we need to update our string.
/// </summary>
void OnEnable()
{
myString.Arguments = new[] { this };
myString.StringChanged += UpdateString;
}
void OnDisable()
{
myString.StringChanged -= UpdateString;
}
void UpdateString(string s)
{
localizedText = s;
}
void OnGUI()
{
// This calls UpdateString immediately (if the table is loaded) or when the table is available.
myString.RefreshString();
GUILayout.Label(localizedText);
}
}
Remove(KeyValuePair<String, IVariable>)
Removes a local variable with the specified key.
Declaration
public bool Remove(KeyValuePair<string, IVariable> item)
Parameters
Type | Name | Description |
---|---|---|
KeyValuePair<String, IVariable> | item | The item to be removed, only the Key field will be considered. |
Returns
Type | Description |
---|---|
Boolean | true if a variable with the specified name was removed, false if one was not. |
Remove(String)
Removes a local variable with the specified name.
Declaration
public bool Remove(string name)
Parameters
Type | Name | Description |
---|---|---|
String | name | The name of the variable to be removed. |
Returns
Type | Description |
---|---|
Boolean | true if a variable with the specified name was removed, false if one was not. |
Examples
This example shows how to remove a local variable.
const string variableName = "my-variable";
localizedString.Add(variableName, new FloatVariable { Value = 100.45f });
Debug.LogFormat("Contains variable before remove: {0}", localizedString.ContainsKey(variableName));
localizedString.Remove(variableName);
Debug.LogFormat("Contains variable after remove: {0}", localizedString.ContainsKey(variableName));
Reset()
Clears the current loading operation.
Declaration
protected override void Reset()
Overrides
TryGetValue(String, out IVariable)
Gets the IVariable with the specified name.
Declaration
public bool TryGetValue(string name, out IVariable value)
Parameters
Type | Name | Description |
---|---|---|
String | name | The name of the variable. |
IVariable | value | The variable that was found or default. |
Returns
Type | Description |
---|---|
Boolean |
Implements
Examples
This example shows how to get and add a local variable using TryGetValue.
FloatVariable playerScore = null;
if (!localizedString.TryGetValue("player-score", out var variable))
{
playerScore = new FloatVariable();
localizedString.Add("player-score", playerScore);
}
else
{
playerScore = variable as FloatVariable;
}
playerScore.Value += 10;
Events
StringChanged
Provides a callback that will be invoked when the translated string has changed. The following events will trigger an update:
- The first time the action is added to the event.
- The SelectedLocale changing.
- If the string is currently using a IVariable which supports IVariableValueChanged and it's value has changed.
- When RefreshString() is called.
- The TableReference or TableEntryReference changing.
Declaration
public event LocalizedString.ChangeHandler StringChanged
Event Type
Type | Description |
---|---|
LocalizedString.ChangeHandler |
Examples
This example shows how the StringChanged event can be used to trigger updates to a string.
public class LocalizedStringWithEvents : MonoBehaviour
{
public LocalizedString myString;
string localizedText;
/// <summary>
/// Register a ChangeHandler. This is called whenever the string needs to be updated.
/// </summary>
void OnEnable()
{
myString.StringChanged += UpdateString;
}
void OnDisable()
{
myString.StringChanged -= UpdateString;
}
void UpdateString(string s)
{
localizedText = s;
}
void OnGUI()
{
EditorGUILayout.LabelField(localizedText);
}
}
ValueChanged
This event is sent when the global variable has changed or wishes to trigger an update to any LocalizedString that is currently using it.
Declaration
public event Action<IVariable> ValueChanged
Event Type
Type | Description |
---|---|
Action<IVariable> |