Get string from Localize table by script

Hello,

I’m trying to write a script that get the localized string.

I’m trying to use
UnityEngine.Localization.Settings.LocalizationSettings.StringDatabase.GetLocalizedStringAsync(table, key)

but I don’t know how to wait response and return the string.

Could you help me?

We have examples in the package samples.
The manual has some examples.
There are also examples in the scripting docs.
I would suggest using the LocalizedString class instead of accessing the databases directly.

Yes,

I tried this code

var stringOperation = LocalizationSettings.StringDatabase.GetLocalizedStringAsync("My String", new object[] { 123 });
    stringOperation.Completed += s =>
    {
        // Example output: "The value is 123"
        Debug.Log(s.Result);
    };

But s.Result is always empty string.

Try passing in the table name before the entry name.

You are using the version that uses the default table so unless you have also configured a default table it wont work.
If its still not working then check that you have a localized value for the current language.

Thanks for your help but nothing works for me.
I’m going crazy :slight_smile:

I think there is a problem with the table loading and also because have to table.

I’ll try to explain.

If the gameobject where I want to load my translations is active when I start the “game” I don’t have any value. I got empty string.

If the gameobject is active later after starting the game it’s ok for my first table named “Localization Table”. But if I tried to get a value into my second table named “StrumPatternTable” I got no translation found for … in StrumPatternTable.

So I think I have two problems :

  1. My Localization tables are not loaded yet when I asked
  2. My second table is not recognized

Here is my entire code where I tried to load a collection within a dropdown :
I’m really new with Unity :slight_smile:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Android;
using UnityEngine.Localization;
using UnityEngine.Localization.Settings;
using UnityEngine.Localization.Tables;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.UI;

public class StrummingPaternHandler : MonoBehaviour
{

    public GameObject ChoiceContainer;
    public GameObject StrummingContainer;
    public Dropdown dropdown;
    public Button GoStrummingButton;


    private Strum strumSelected;
    private Dictionary<int, Strum> strumsPatternsInDropDown = new Dictionary<int, Strum>();
    private string m;

    string getLocalString(string table, string key)
    {
        // Sometimes the localized value may not be immediately available.
        // The Localization system may not have been initialized yet or the String Table may need loading.
        // The AsyncOperation wraps this loading operation. We can yield on it in a coroutine,
        // use its various Completed Events or await its Task if using async and await.
        var stringOperation = LocalizationSettings.StringDatabase.GetLocalizedStringAsync(table, key);
        if (stringOperation.IsDone)
        {
            SetString(stringOperation);
            return m;
        }

        StartCoroutine(LoadStringWithCoroutine(stringOperation));
        return m;
    }

    IEnumerator LoadStringWithCoroutine(AsyncOperationHandle<string> stringOperation)
    {
        yield return stringOperation;
        SetString(stringOperation);
    }

    void SetString(AsyncOperationHandle<string> stringOperation)
    {
        // Its possible that something may have gone wrong during loading. We can handle this locally
        // or ignore all errors as they will still be captured and reported by the Localization system.
        if (stringOperation.Status == AsyncOperationStatus.Failed)
            m = "Failed to load string";
        else
            m = stringOperation.Result;
    }

    string GetLocalizedString(StringTable table, string entryName)
    {
        // Get the table entry. The entry contains the localized string and Metadata
        var entry = table.GetEntry(entryName);
        return entry.GetLocalizedString(); // We can pass in optional arguments for Smart Format or String.Format here
    }


    private void Start()
    {
        dropdown.options.Clear();

        StrumCollection strumCollection = new StrumCollection();
        Dictionary<string, Strum> strumsPatterns = strumCollection.getStrums();

        int i = 0;

        foreach (KeyValuePair<string, Strum> s in strumsPatterns)
        {
            Strum strum = s.Value;
            //string value = LocalizationUtils.getTranslationMessage(strum.levelKey, "StrumPatternTable");
            string value = getLocalString("LocalizationTable", "go");
            value += " - ";           
            value += getLocalString("StrumPatternTable", strum.strokes);

            dropdown.options.Add(new Dropdown.OptionData()
            {
                text = value
            });
           
            strumsPatternsInDropDown.Add(i, strum);
            i++;
        }

        dropdown.RefreshShownValue();

        DropdownItemSelected(dropdown);

        dropdown.onValueChanged.AddListener(delegate { DropdownItemSelected(dropdown); });
        GoStrummingButton.onClick.AddListener(delegate { GoToStrumming(); });
    }

    void DropdownItemSelected(Dropdown dropdown)
    {
        int index = dropdown.value;

        strumSelected = strumsPatternsInDropDown[index];

        CurrentStrum.strum = strumSelected;
    }

    void GoToStrumming()
    {
        Strum strum = strumSelected;
       
        StrummingContainer.SetActive(true);
        ChoiceContainer.SetActive(false);
    }

    public void GoBack()
    {
        StrummingContainer.SetActive(false);
        ChoiceContainer.SetActive(true);
    }

    private void Update()
    {
       
    }
}

Yes, your getLocalString method is not waiting for it to complete. I would just use the synchronous methods instead.
Use GetLocalizedString instead of GetLocalizedStringAsync.
Is this script just to localize a Dropdown? You can use the localized property variants to do that.

https://docs.unity3d.com/Packages/com.unity.localization@1.4/manual/LocalizedPropertyVariants.html

Thanks I’ll tried.

But first, is there something to call to be sure Localization tables are loaded at start?

By default we dont load all the tables at start, we only load them when they are needed.
You can enable preloading if you want them to be loaded String Tables | Localization | 1.4.5

This will happen during initialization.
You can call LocalizationSettings.InitializationOperation.WaitForCompletion() to force them to be loaded at the start.

Yes I see this documentation on preloading but I don’t have this option.

I have version 1.3.2 of Localization. I think this option have to be there but I don’t have the right part of the windows.

You need to click the metadata icon next to the language name in the table editor window

OK thanks, it seems to work now.
I don’t know what happens before because I do that at first.

Now, I have to reload those values when users change language from the UI. I don’t know how :slight_smile:

If you use the LocalizedString.StringChanged event then it will call this when the language changes.
You can also use LocalizationSettings.SelectedLocaleChanged.

oH yes it works :slight_smile:
Thank you!

I can now publish my app in english too :slight_smile: