docs.unity3d.com
Search Results for

    Show / Hide Table of Contents

    Class LocalizedString

    Provides a way to reference a StringTableEntry inside of a specific StringTable and request the localized string.

    Inheritance
    object
    LocalizedReference
    LocalizedString
    Implements
    ISerializationCallbackReceiver
    IVariableGroup
    IVariableValueChanged
    IVariable
    Inherited Members
    LocalizedReference.m_CurrentTable
    LocalizedReference.m_CurrentTableEntry
    LocalizedReference.TableReference
    LocalizedReference.TableEntryReference
    LocalizedReference.FallbackState
    LocalizedReference.LocaleOverride
    LocalizedReference.WaitForCompletion
    LocalizedReference.IsEmpty
    LocalizedReference.SetReference(TableReference, TableEntryReference)
    Namespace: UnityEngine.Localization
    Assembly: Unity.Localization.dll
    Syntax
    [Serializable]
    public class LocalizedString : LocalizedReference, ISerializationCallbackReceiver, IVariableGroup, IVariableValueChanged, IVariable
    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);
            }
        }
    }

    This example shows how to bind to a UI Toolkit property. Note that this requires Unity 2023.2 and above.

    using UnityEngine;
    using UnityEngine.Localization;
    using UnityEngine.UIElements;
    
    public class LocalizedStringUIDocumentExample : MonoBehaviour
    {
        void Start()
        {
            var document = GetComponent<UIDocument>();
    
            var label = new Label();
            label.text = "Default Text";
            document.rootVisualElement.Add(label);
    
            // Add binding to the text property of the label.
            var localizedString = new LocalizedString("My table", "My Entry");
            label.SetBinding("text", localizedString);
        }
    }

    This example shows how to use local variables when you bind to a UI Toolkit property. Note that this requires Unity 2023.2 and above.

    using UnityEngine;
    using UnityEngine.Localization;
    using UnityEngine.Localization.SmartFormat.PersistentVariables;
    using UnityEngine.UIElements;
    
    [RequireComponent(typeof(UIDocument))]
    public class LocalizedStringVariablesUIDocumentExample : MonoBehaviour
    {
        IntVariable m_Counter;
    
        void Start()
        {
            var document = GetComponent<UIDocument>();
    
            var label = new Label();
            document.rootVisualElement.Add(label);
    
            // Add binding to the text property of the label.
            // Example Smart string "The current count is {counter}."
            m_Counter = new IntVariable { Value = 1 };
            var localizedString = new LocalizedString("My Table", "My Entry");
    
            // Add the variable
            localizedString.Add("counter", m_Counter);
    
            label.SetBinding("text", localizedString);
    
            // Localize the button labels
            var buttonIncrement = new Button();
            var buttonDecrement = new Button();
            buttonIncrement.SetBinding("text", new LocalizedString("My Table", "Increment Button Label"));
            buttonDecrement.SetBinding("text", new LocalizedString("My Table", "Decrement Button Label"));
            buttonIncrement.clicked += () => m_Counter.Value++;
            buttonDecrement.clicked += () => m_Counter.Value--;
    
            document.rootVisualElement.Add(buttonIncrement);
            document.rootVisualElement.Add(buttonDecrement);
            document.rootVisualElement.Add(label);
        }
    }

    Constructors

    Name Description
    LocalizedString()

    Initializes and returns an empty instance of a LocalizedString.

    LocalizedString(TableReference, TableEntryReference)

    Initializes and returns an instance of a LocalizedString.

    Properties

    Name Description
    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.

    Count

    Returns the number of local variables inside this localized string.

    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 UnityEngine.ResourceManagement.AsyncOperations.AsyncOperationHandle. See also RefreshString()

    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 UnityEngine.ResourceManagement.AsyncOperations.AsyncOperationHandle. See also RefreshString()

    HasChangeHandler

    Returns true if StringChanged has any subscribers.

    IsReadOnly

    Implemented as part of the IDictionary interface but not actually used. Will always return false.

    this[string]

    Gets or sets the IVariable with the specified name.

    Keys

    Returns a collection containing all the unique local variable names.

    Values

    Returns all the local variables for this localized string.

    Methods

    Name Description
    Add(KeyValuePair<string, IVariable>)

    Adds a new Local Variable to use during formatting.

    Add(string, IVariable)

    Adds a new Local Variable to use during formatting.

    Clear()

    Removes all local variables.

    ClearChangeHandler()
    Contains(KeyValuePair<string, IVariable>)

    Returns true if a local variable with the specified name exists.

    ContainsKey(string)

    Returns true if a local variable with the specified name exists.

    CopyTo(KeyValuePair<string, IVariable>[], int)

    Copies the local variables into an array starting at arrayIndex.

    ForceUpdate()
    GetEnumerator()

    Returns an enumerator for all local variables in this localized string.

    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.

    GetLocalizedString(IList<object>)

    Provides a translated string from a StringTable with the TableReference and the translated string that matches TableEntryReference.

    GetLocalizedString(params 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.

    GetLocalizedStringAsync()

    Provides a translated string from a StringTable with the TableReference and the translated string that matches TableEntryReference.

    GetLocalizedStringAsync(IList<object>)

    Provides a translated string from a StringTable with the TableReference and the translated string that matches TableEntryReference.

    GetLocalizedStringAsync(params object[])

    Provides a translated string from a StringTable with the TableReference and the translated string that matches TableEntryReference.

    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.

    RefreshString()

    Provides a way to force a refresh of the string when using StringChanged.

    RegisterChangeHandler(ChangeHandler)
    Remove(KeyValuePair<string, IVariable>)

    Removes a local variable with the specified key.

    Remove(string)

    Removes a local variable with the specified name.

    Reset()

    Clears the current loading operation.

    TryGetValue(string, out IVariable)

    Gets the IVariable with the specified name.

    Events

    Name Description
    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.
    When the first LocalizedString.ChangeHandler is added, a loading operation (see CurrentLoadingOperationHandle) automatically starts. When the loading operation is completed, the localized string value is sent to the subscriber. If you add additional subscribers after loading has completed, they are also sent the latest localized string value. This ensures that a subscriber will always have the correct localized value regardless of when it was added.
    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.

    In This Article
    Back to top
    Copyright © 2024 Unity Technologies — Trademarks and terms of use
    • Legal
    • Privacy Policy
    • Cookie Policy
    • Do Not Sell or Share My Personal Information
    • Your Privacy Choices (Cookie Settings)