Skip to main content

Localization

Important Attention Reminder

Coding Style wiki


Localization is the localization core of the LocalizationSystem (all members are static). The project supplies the supported languages and language table parsing via callbacks (onAddSupportedLanguages, onParsingLanguageData, onChangeLanguage), and the class provides language switching (ChangeLanguage), system-language detection, and code-to-text lookup (GetStringByCode) APIs; see the Module Intro for the full initialization flow.

NamespaceOxGKit.LocalizationSystem
Typepublic class Localization (all members are static)
SourceLocalization.cs
using OxGKit.LocalizationSystem;

Quick Start

using System.Collections.Generic;
using OxGKit.LocalizationSystem;

// 1. Declare the supported languages
Localization.onAddSupportedLanguages = (supportedLanguages) =>
{
supportedLanguages.Add(LangType.English);
supportedLanguages.Add(LangType.ChineseTraditional);
};

// 2. Provide language table parsing (data source is up to the project: JSON, spreadsheet exports, a server...)
Localization.onParsingLanguageData = (langType, langData) =>
{
foreach (var pair in langSheet[langType.ToString()])
langData.TryAdd(pair.Key, pair.Value);
return true; // return true on success
};

// 3. Refresh UI texts after a successful language switch
Localization.onChangeLanguage = (langType) => RefreshAllLocalizedTexts();

// 4. First switch (e.g. use the system language; automatically falls back to English when unsupported)
Localization.ChangeLanguage(Localization.systemLanguage);

// 5. The UI always looks up texts by code
string title = Localization.GetStringByCode("ui.title");

General Rules

Required Callbacks

  1. Assign onAddSupportedLanguages to declare the supported languages.
  2. Assign onParsingLanguageData to provide language table parsing (the data source needed for parsing must be prepared first).
  3. (Recommended) Subscribe to onChangeLanguage to refresh UI texts.

Important When onParsingLanguageData is unassigned or parsing returns false, ChangeLanguage throws an exception.

Caching Mechanism

Attention GetSupportedLanguages and the mapping-table APIs cache their result on the first call (the callback is not fired again), so you must assign onAddSupportedLanguages first, before calling any supported-language related API (including systemLanguage, IsSupportedLanguage, etc.).

Persisting the Language

Reminder The module does not persist the selected language; the project owns saving/restoring the LangType. When restoring, it is recommended to sanitize the value with GetAndCheckIsSupportedLanguage first.


Callback Members

Member Overview

MemberDescription
onAddSupportedLanguagesCallback that adds the supported languages.
onParsingLanguageDataCallback that parses the language table data (invoked by ChangeLanguage).
onChangeLanguageCallback fired after a successful language switch.

onAddSupportedLanguages

public static Action<HashSet<LangType>> onAddSupportedLanguages

Callback that adds the supported languages; fired the first time GetSupportedLanguages is called. Add the languages your project supports to the supportedLanguages set.

Localization.onAddSupportedLanguages = (supportedLanguages) =>
{
supportedLanguages.Add(LangType.English);
supportedLanguages.Add(LangType.ChineseTraditional);
supportedLanguages.Add(LangType.ChineseSimplified);
supportedLanguages.Add(LangType.Japanese);
supportedLanguages.Add(LangType.Korean);
};

onParsingLanguageData

public static Func<LangType, Dictionary<string, string>, bool> onParsingLanguageData

Callback that parses the language table data; invoked by ChangeLanguage. Fill the Code -> Text pairs of the given language into langData (after a successful switch, that dictionary is cached as the current language table), and return true on success.

Localization.onParsingLanguageData = (langType, langData) =>
{
// Your lang sheet (can load from json or server)
if (langSheet.ContainsKey(langType.ToString()))
{
// The ref langData will be cached by Localization
foreach (var pair in langSheet[langType.ToString()])
langData.TryAdd(pair.Key, pair.Value);
return true;
}
return false;
};

Important When unassigned or returning false, ChangeLanguage throws an exception; the data source needed for parsing (game database, downloaded language tables, etc.) must be prepared before initializing localization.

onChangeLanguage

public static Action<LangType> onChangeLanguage

Notification callback fired after a successful language switch; the parameter is the language switched to. This is the place to refresh the UI display texts (together with GetStringByCode).

private void _InitEvents()
{
// Refresh lang text callback
Localization.onChangeLanguage += this._RefreshLanguage;
}

private void _RefreshLanguage(LangType langType)
{
this.titleText.text = Localization.GetStringByCode("ui.title");
}

Reminder Fired on every successful switch, so the handler must be repeat-safe (only redraw texts/data; do not perform one-time registrations inside it).


Properties

Member Overview

MemberDescription
currentLanguageThe current language (read-only).
systemLanguageThe system language (checked against the supported languages; falls back to English when unsupported).

currentLanguage

public static LangType currentLanguage { get; private set; }

The current language (read-only); its initial value comes from systemLanguage, and it is only updated after a successful ChangeLanguage.

// Save the selected language (the module does not persist it)
PlayerPrefs.SetInt("language", (int)Localization.currentLanguage);

systemLanguage

public static LangType systemLanguage { get; }

Gets the system language: maps the OS language via GetSystemLanguageToLangType to a LangType, then checks it with GetAndCheckIsSupportedLanguage; when it is not a supported language, it always falls back to LangType.English.

// On first launch without a saved language, use the system language as the default
Localization.ChangeLanguage(Localization.systemLanguage);

Language Switching and Text Lookup

Method Overview

MethodDescription
ChangeLanguageSwitches the language and validates it.
GetStringByCodeGets the corresponding text from the language table by code.

ChangeLanguage

public static void ChangeLanguage(LangType langType)

Switches the language and validates it. The flow is:

  1. Invokes onParsingLanguageData to parse the language table of the given language.
  2. Verifies whether langType is a supported language:
    • Yes: caches the language table data, updates currentLanguage, and fires onChangeLanguage.
    • No: logs a warning (The language type is not supported) and keeps the current language (no update, no callback).
Localization.ChangeLanguage(LangType.Japanese);

// Save the selected language (the module does not persist it)
PlayerPrefs.SetInt("language", (int)Localization.currentLanguage);

Important When onParsingLanguageData is unassigned or parsing fails (returns false), an Exception is thrown.

Attention Sanitize the value with GetAndCheckIsSupportedLanguage before passing it in (to avoid a saved legacy language value that is no longer supported).

GetStringByCode

public static string GetStringByCode(string code)

Gets the corresponding text from the current language table by code; returns "Unknown Text" when the code is not found.

this.titleText.text = Localization.GetStringByCode("ui.title");

Attention Throws an Exception if ChangeLanguage has never succeeded yet (no language table data); during QA, treat "Unknown Text" as a missing string code signal.


Supported Language Queries

Method Overview

MethodDescription
GetSupportedLanguagesGets the current supported-language set.
IsSupportedLanguageWhether the language is supported.
GetAndCheckIsSupportedLanguageChecks the language; always returns English when unsupported.
GetSystemLanguageToLangTypeGets the LangType definition corresponding to the system language.
GetSupportedLanguagesMappingByLangTypeGets the language description mapping table (Key = LangType).
GetSupportedLanguagesMappingByLangDescGets the language description mapping table (Key = LangDesc).

GetSupportedLanguages

public static HashSet<LangType> GetSupportedLanguages()

Gets the current supported-language set; the first call fires onAddSupportedLanguages to collect and cache the set, and subsequent calls return the cached result directly.

IsSupportedLanguage

public static bool IsSupportedLanguage(LangType langType)

Whether the language is a supported language.

GetAndCheckIsSupportedLanguage

public static LangType GetAndCheckIsSupportedLanguage(LangType langType)

Gets and checks whether the language is a supported language: returns the value as-is when supported; always returns LangType.English when unsupported. Suitable for sanitizing saved/system values.

var savedLang = (LangType)PlayerPrefs.GetInt("language", (int)Localization.systemLanguage);
Localization.ChangeLanguage(Localization.GetAndCheckIsSupportedLanguage(savedLang));

GetSystemLanguageToLangType

public static LangType GetSystemLanguageToLangType()

Gets the LangType definition corresponding to the OS language (UnityEngine.Application.systemLanguage) (without the supported-language check); returns LangType.Unspecified when it cannot be mapped.

Reminder Some languages are not built into Unity's SystemLanguage (see the System Detection column of the LangType table); system detection can never return them, but they can still be used as custom supported languages. Hindi requires Unity 2022.3 / Unity 6000.0 or higher for detection.

GetSupportedLanguagesMappingByLangType

public static Dictionary<LangType, string> GetSupportedLanguagesMappingByLangType()

Gets the language description mapping table of the supported languages, with Key = LangType (ex: LangType.Spanish -> "Español"); suitable for generating the display texts of a language menu (cached after the first call).

GetSupportedLanguagesMappingByLangDesc

public static Dictionary<string, LangType> GetSupportedLanguagesMappingByLangDesc()

Gets the language description mapping table of the supported languages, with Key = LangDesc (ex: "Español" -> LangType.Spanish); suitable for a language menu to look up the language from the selected option text for switching (cached after the first call).

// Language menu: display options with the mapped descriptions,
// then look up the LangType from the selection to switch
var mapping = Localization.GetSupportedLanguagesMappingByLangDesc();
Localization.ChangeLanguage(mapping["English"]);

LangType

World language definitions (a byte enum) with 72 values in total (Unspecified + 71 world languages).

Typepublic enum LangType : byte
SourceLanguages.cs

Table legend:

  • Description = the language display text returned by LanguageMapping.GetLanguageDesc.
  • System Detection = whether GetSystemLanguageToLangType can return the value; ✗ means the language is not built into Unity's SystemLanguage (it can never come from system detection, but can still be used as a custom supported language).
Enum ValueLanguageDescriptionSystem Detection
UnspecifiedUnspecified✓ (fallback when unmappable)
ArabicArabicالعربية
ChineseSimplifiedSimplified Chinese简体中文
ChineseTraditionalTraditional Chinese繁體中文
DutchDutchNederlands
EnglishEnglishEnglish
FrenchFrenchFrançais
GermanGermanDeutsch
ItalianItalianItaliano
PortuguesePortugueseProtuguês
SpanishSpanishEspañol
BengaliBengaliবাংলা
CroatianCroatianhrvatski
CzechCzechčeština
DanishDanishDansk
GreekGreekελληνικά
HebrewHebrewעברית
HindiHindiहिंदी✓ (Unity 2022.3+)
HungarianHungarianMagyar
IndonesianIndonesianBahasa Indonesia
JapaneseJapanese日本語
KoreanKorean한국의
MalayMalayBahasa Melayu
PerisanPersianفارسی
PolishPolishPolski
RomanianRomanianromâna
RussianRussianРусский
SerbianSerbianсрпски
SwedishSwedishSvenska
ThaiThaiไทย
TurkishTurkishTürkçe
UrduUrduاردو
VietnameseVietnamesetiếng việt
CatalanCatalan (Spain)catalá
LatvianLatvianLatviski
LithuanianLithuanianLietuvių
NorwegianNorwegianNorsk bokmal
SlovakSlovakSlovenčina
SlovenianSlovenianSlovenščina
BulgarianBulgarianбългарски
UkrainianUkrainianукраїнська
FilipinoFilipinoTagalog
FinnishFinnishSuomi
AfrikaansAfrikaansAfrikaans
RomanshRomansh (Switzerland)Rumantsch
BurmeseBurmese (official)ဗမာ
KhmerKhmerខ្មែរ
AmharicAmharic (Ethiopia)አማርኛ
BelarusianBelarusianбеларуская
EstonianEstonianeesti
SwahiliSwahili (Tanzania)Kiswahili
ZuluZulu (South Africa)isiZulu
AzerbaijaniAzerbaijaniazərbaycanca
ArmenianArmenian (Armenia)Հայերէն
GeorgianGeorgian (Georgia)ქართული
LaotianLao (Laos)ລາວ
MongolianMongolianМонгол
NepaliNepaliनेपाली
KazakhKazakhқазақ тілі
GalicianGalicianGalego
IcelandicIcelandicíslenska
KannadaKannadaಕನ್ನಡ
KyrgyzKyrgyzкыргыз тили; قىرعىز تىلى
MalayalamMalayalamമലയാളം
MarathiMarathiमराठी
TamilTamilதமிழ்
MacedonianMacedonianмакедонски јазик
TeluguTeluguతెలుగు
UzbekUzbekЎзбек тили
BasqueBasqueEuskara
SinhalaSinhala (Sri Lanka)සිංහල
FaroeseFaroeseFøroyskt

Attention The enum value for Persian is spelled Perisan, and the description of Portuguese is "Protuguês" (both are the actual definitions in the source code; always follow the source when using them).


LanguageMapping

Mapping helper (static class) between the language type and its display description.

Typepublic static class LanguageMapping
SourceLanguageMapping.cs

GetLanguageDesc

public static string GetLanguageDesc(LangType langType)

Gets the corresponding language description (see the LangType table); returns "Unknown Language" when no description is defined.

string desc = LanguageMapping.GetLanguageDesc(LangType.Spanish); // "Español"