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
public class LocalizedString : LocalizedReference, IVariableGroup, IDictionary<string, IVariable>, IVariableValueChanged, IVariable
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 |
TableEntryReference | entryReference | Reference to the String Table Collection entry.
This can either be the name of the Key as a |
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 |
CurrentLoadingOperation
The current loading operation for the string when using StringChanged or null 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
Declaration
public AsyncOperationHandle<LocalizedDatabase<StringTable, StringTableEntry>.TableEntryResult>? CurrentLoadingOperation { get; }
Property Value
Type | Description |
---|---|
Nullable<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);
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);
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 |
|
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 |
|
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. |
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 |
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 |
Returns
Type | Description |
---|---|
String |
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 |
Returns
Type | Description |
---|---|
String |
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
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
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 |
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 |
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 |
Remarks
This will only force the refresh if there is currently no active CurrentLoadingOperation, 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.
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 |
|
Remove(String)
Removes a local variable with the specified name.
Declaration
public bool Remove(string name)
Parameters
Type | Name | Description |
---|---|---|
String | name |
Returns
Type | Description |
---|---|
Boolean |
|
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 |
Returns
Type | Description |
---|---|
Boolean |
|
Implements
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> |