Urho3D

The Localization subsystem provides a simple way to creating multilingual applications.

Initialization

Before using the subsystem, the localization string collection(s) need to be loaded. A common practice is to do this at application startup. Multiple collection files can be loaded, and each can define either just one or several languages. For example:

Localization* l10n = GetSubsystem<Localization>();
// 1st JSON file format
l10n->LoadJSONFile("StringsEnRu.json");
l10n->LoadJSONFile("StringsDe.json");
// 2nd JSON file format
l10n->LoadJSONFile("StringsLv.json", "lv");

JSON files must be in UTF8 encoding without BOM. Sample files are in the bin/Data directory. The JSON files must have one of the following formats:

  1. LoadJSONFile("StringsEnRu.json") method will automatically pick the language from the JSON file
    {
    "string id 1":{
    "language 1":"value11",
    "language 2":"value12",
    "language 3":"value13"
    },
    "string id 2":{
    "language 1":"value21",
    "language 2":"value22",
    "language 3":"value23"
    }
    }
  2. You must pass 2nd argument to the LoadJSONFile("StringsLv.json", "lv") method to tell the parser which language will be loaded
    {
    "string id 1": "value 1",
    "string id 2": "value 2",
    "string id 3": "value 3"
    }

Any number of languages can be defined. Remember that language names and string identifiers are case sensitive. "En" and "en" are considered different languages. During the loading process languages are numbered in order of finding. Indexing starts from zero. The first found language is set to be initially active.

Using

The Get function returns a string with the specified string identifier in the current language.

Text* t = new Text(context_);
t->SetName("Text1");
Localization* l10n = GetSubsystem<Localization>();
t->SetText(l10n->Get("string 1"));

If the string id is empty, an empty string will be returned. If the translation is not found, the id will be returned unmodified and a warning will be logged.

Use SetLanguage() function to change language at runtime.

Localization* l10n = GetSubsystem<Localization>();
l10n->SetLanguage("language 2");

When the language is changed, the E_CHANGELANGUAGE event will be sent. Subscribe to it to perform the necessary relocalization of your user interface (texts, sprites etc.)

SubscribeToEvent(E_CHANGELANGUAGE, URHO3D_HANDLER(Game, HandleChangeLanguage));
void Game::HandleChangeLanguage(StringHash eventType, VariantMap& eventData)
{
Localization* l10n = GetSubsystem<Localization>();
...
Text* t = static_cast<Text*>(uiRoot->GetChild("Text1", true));
t->SetText(l10n->Get("string 1"));
}

Text UI elements also support automatic translation to avoid manual work.

Text* t2 = new Text(context_);
t2->SetText("string 2");
t2->SetAutoLocalizable(true);

Wherein text value is used as an identifier.

Also see the example 40_Localization.