Skip to content

About

C# classes and properties generator from Unity Localization tables

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

111 Commits

Folders and files

Repository files navigation

Localization Codegen

Localization Codegen

Strongly typed C# access to your Unity Localization tables
Write code instead of hitting the localization database with magic strings

OpenUPM Downloads Unity 2021.3+ UniTask optional MIT License

Quick start • Installation • Usage • Settings • CI • Changelog


Overview

Localization Codegen reads your Unity Localization table collections and generates plain C# classes for them – one static class per collection, one member per key. No runtime reflection, no string lookups in your game code, and full autocomplete plus compile-time safety.

// Before
label.text = LocalizationSettings.StringDatabase.GetLocalizedString("Ui", "HelloWorld");

// After
label.text = Ui.HelloWorld;
Feature Description
🧩 Typed access One static class per string or asset table collection, one member per key
💬 Smart strings Entries with placeholders become methods with typed positional and named parameters
🔗 Reference members Optional Ref class with LocalizedString / LocalizedAsset<T> references that follow locale changes
⚡ UniTask Optional …Async members returning UniTask, with cancellation
🔁 Automatic regeneration Regeneration when tables are saved, including changes pulled from version control
🧪 CI ready Batch mode entry points to regenerate, or to fail when generated code is out of date
🪄 First-run wizard A setup wizard opens after the package is first imported

Quick start

  1. Install the package with OpenUPM:

    openupm add com.severnbli.localization-codegen
  2. Finish the setup wizard. It picks a namespace and an output folder and runs the first generation.

  3. Use the generated classes:

    using Localization;
    
    label.text = Ui.HelloWorld;

Edit your tables as usual – the classes regenerate when you save them.

Installation

Pick one variant. Do not mix them: the UPM package and the .unitypackage variants both provide assemblies named com.severnbli.localization-codegen.Runtime / .Editor, so installing two of them causes duplicate assembly errors.

Variant Updates Dependencies Version tracking
OpenUPM Package Manager automatic manifest + lock file
Signed tarball manual URL edit automatic manifest entry
Installer .unitypackage one-shot manifest edit automatic manifest + lock file
Standard .unitypackage manual re-import manual you

The setup wizard opens after the first compilation in every case.

Option 1 – OpenUPM (recommended)

The package is published on OpenUPM as com.severnbli.localization-codegen.

  1. Install the OpenUPM CLI (requires Node.js):

    npm install -g openupm-cli
  2. Open a terminal in your Unity project folder (the one containing Assets/ and Packages/) and run:

    openupm add com.severnbli.localization-codegen
  3. Switch back to Unity. The package resolves, compiles, and the setup wizard opens.

Tip

openupm add handles the scoped registry, dependency resolution and manifest.json changes for you. You can also add the package from Window > Package Manager if the OpenUPM registry is already configured.

Manual installation (without the CLI)

Add the scoped registry and the dependency to Packages/manifest.json:

{
  "scopedRegistries": [
    {
      "name": "OpenUPM",
      "url": "https://package.openupm.com",
      "scopes": [
        "com.severnbli.localization-codegen"
      ]
    }
  ],
  "dependencies": {
    "com.severnbli.localization-codegen": "1.3.4"
  }
}

Then let Unity refresh the project. Replace the version with the latest one shown on the badge above.

Package Manager resolves com.unity.localization for you and keeps the version in Packages/packages-lock.json.

Option 2 – Signed tarball (.tgz)

Every release ships a signed UPM tarball, tarball-com.severnbli.localization-codegen-<version>.tgz, which is the same artifact OpenUPM consumes. Add it as a file dependency:

{
  "dependencies": {
    "com.severnbli.localization-codegen": "https://github.com/Severnbli/localization-codegen/releases/download/<version>/tarball-com.severnbli.localization-codegen-<version>.tgz"
  }
}

Unity resolves the package's own dependencies from the tarball, so com.unity.localization is pulled in as usual. Packages installed from a URL are not updated automatically – editing the URL or version by hand is the update. It also works for offline machines: download the file once and reference it with a file: path. The .attestation.p7m signature inside the archive is what OpenUPM verifies; Unity itself does not.

Option 3 – Installer .unitypackage

Download installer-com.severnbli.localization-codegen-<version>.unitypackage from the release and import it (Assets > Import Package > Custom Package). It contains only an editor script under Assets/Editor/Localization Codegen Installer/, which on the next domain reload:

  • registers the OpenUPM scoped registry in Packages/manifest.json, and
  • pins com.severnbli.localization-codegen to the installer's version.

Package Manager then downloads and manages the real package, so dependencies resolve automatically and updates work as in Option 1. The installer never downgrades: it only writes the version when the installer's version is newer than the one already pinned.

Option 4 – Standard .unitypackage (manual versioning)

Download com.severnbli.localization-codegen-<version>.unitypackage from the release and import it. Sources land in Assets/Plugins/LocalizationCodegen/. Committed .meta GUIDs are preserved, so script references survive a re-import and a later upgrade.

This variant bypasses Package Manager, so versioning is manual:

  • No package.json is included, so Unity does not know which version is installed and Package Manager cannot list, update or uninstall it. Record the version yourself – keep the versioned release file or note it in your changelog.
  • To update, delete Assets/Plugins/LocalizationCodegen/ and import the newer .unitypackage. There are no partial upgrades, and stale files are not cleaned up.
  • Install the com.unity.localization dependency yourself. Nothing resolves it for you.

Requirements

Requirement Version
Unity 2021.3 or newer
com.unity.localization 1.5.x (automatic with the UPM variants, manual with the standard .unitypackage)
com.cysharp.unitask 2.x, optional – only for UniTask members

Usage

Generated classes

Given a string table collection named Ui containing the key HelloWorld, the generator produces Ui.g.cs:

// <auto-generated by Localization Codegen>
// Table collection: Ui
using Severnbli.LocalizationCodegen;

namespace Localization
{
    public static class Ui
    {
        public const string TableName = "Ui";

        public static string HelloWorld => LocalizedTables.GetString(TableName, "HelloWorld");
    }
}

Each file imports the namespaces it needs with ordinary using directives at the top and refers to every type (LocalizedTables, LocalizedString, asset types, Dictionary<,>) by its short name. When a short name could bind to another type – two asset types with the same name, a nested class created by a key separator, or a type with that name in your namespace – only that type stays global::-qualified.

Use it anywhere from your game code:

using Localization;

label.text = Ui.HelloWorld;

For asset table collections, each member is typed from the entry's asset type (falling back to UnityEngine.Object) and returns the localized asset:

Sprite icon = Icons.Sword;

Naming rules

Generated identifiers always stay valid C#:

  • Invalid characters become _.
  • Names starting with a digit get a _ prefix.
  • C# keywords get an @ prefix.
  • Collisions get a numeric suffix, assigned by entry id so older keys keep their names.
  • Class names collide case-insensitively (Ui and UI get separate files on Windows/macOS).
  • Reserved names (System, UnityEngine, Unity, the first namespace segment, …) and the names of types the generated code refers to (LocalizedTables, Dictionary, Sprite, …) get a Table suffix.
  • Windows device names (CON, NUL, COM1, …) get a trailing _.

With Naming Convention = PascalCase and optional Key Separators, player name becomes PlayerName and Menu/Start becomes the nested class Menu.Start. These options are off by default, so upgraded projects keep their existing API.

Smart strings

Enable Smart Strings = Methods to turn entries that need arguments into methods:

// "{0}, you have {count:plural:one item|{} items}"
public static string Greeting(object arg0, int count)
    => LocalizedTables.GetStringMixed(TableName, "Greeting", new object[] { arg0 },
        new Dictionary<string, object> { ["count"] = count });
  • Positional placeholders ({0}) become arg0, arg1, … (gaps are filled).
  • Named placeholders ({player-name}, {player.Name}) become camelCase parameters. The original name is preserved for the runtime lookup.
  • {} (the current value inside a formatter) is not a parameter.
  • Variables provided by a Global Variables Group are not parameters; Unity resolves them.
  • Smart Parameter Types = Inferred uses int for plural, IEnumerable for list, otherwise object.
  • Smart Parameter Types = Mapping uses the types you set in the entry's Smart Parameter Types metadata and infers the rest like Inferred.
  • Changing Smart Strings or Smart Parameter Types asks whether to regenerate, since method signatures change. So does every other setting that changes the generated code, unless Silently On Settings Change is on.
  • Placeholder differences between locales are reported as warnings. Enable Fail CI On Smart String Mismatch to make CheckBatch fail on them.
  • MethodsAndRefs additionally emits Ref.Greeting(...) returning a LocalizedString whose arguments and local variables are set.

Note

Smart strings are opt-in. Upgraded projects default to Off; new projects default to Methods when the setup wizard completes.

Parameter types

With Smart Parameter Types = Mapping, you choose parameter types per entry. The types are stored as entry metadata, so the text players see never changes.

  1. Open the collection in Window > Asset Management > Localization Tables and open the metadata of the key (shared by all locales).
  2. Add Localization Codegen / Smart Parameter Types.
  3. Click Add All Parameters to add a row for every variable the entry uses in any locale, pre-filled with the inferred type, then change the types you care about. Add Parameter adds a single variable.
  4. Each row's name is a dropdown of the entry's variables, labelled with their formatters and locales (count (plural; en, ru)). A warning icon marks a row that generation would warn about; hover it for the reason.

Metadata edits regenerate when you save the table (File > Save Project or Ctrl+S), not on every click. Turn on On Metadata Edit to regenerate after each edit instead.

Rows you delete simply fall back to the inferred type. Outside the Table Editor, names can be typed by hand: the variable name as written in the string (count, or 0 for {0}).

// "{player} has {count:plural:one coin|{} coins}" with player = String, count = Int
public static string Coins(int count, string player)
    => LocalizedTables.GetString(TableName, "Coins",
        new Dictionary<string, object> { ["count"] = count, ["player"] = player });
Type C# type
Object object
String string
Int, Long, Float, Double, Decimal, Bool, Char int, long, float, double, decimal, bool, char
DateTime System.DateTime
List System.Collections.IEnumerable

Parameters without a row are inferred. These cases are reported as warnings:

  • A type that plural cannot format (String, Bool, Char, DateTime, Object) on a variable used with plural. plural needs a number or a collection.
  • A type other than List on a variable used with list.
  • A row whose name is not a parameter of the entry (for example after renaming a placeholder), a row without a name, and a name listed twice (the first row wins).

Reference members

The regular members return a value: Ui.HelloWorld is the text in the current locale at the moment you read it. When the player switches language, a label you filled that way keeps the old text.

Enable Generate Reference Members to also get a nested Ref class that returns a reference to the entry instead – Unity's own LocalizedString (or LocalizedAsset<T> for asset tables), which knows which entry it points at and can follow locale changes:

public static class Ref
{
    public static LocalizedString HelloWorld
        => new LocalizedString(TableName, "HelloWorld");
}

Use it wherever Unity Localization expects a reference – still without magic strings:

// A LocalizeStringEvent component updates its label whenever the locale changes.
localizeStringEvent.StringReference = Ui.Ref.HelloWorld;

// Or react to locale changes yourself.
var title = Ui.Ref.HelloWorld;
title.StringChanged += text => label.text = text;

Asset entries use LocalizedSprite, LocalizedAudioClip, LocalizedAsset<T> and the other built-in localized asset types when available. Each access creates a new reference, so keep the one you subscribed to.

Loading a table

Enable Load Table Method to give every table class a LoadTable() method that loads the table for the selected locale without blocking:

public static Task<StringTable> LoadTable() => LocalizedTables.LoadStringTable(TableName);
await Ui.LoadTable();      // e.g. behind a loading screen
label.text = Ui.HelloWorld; // the table is loaded, so this does not wait
  • Asset table classes return Task<AssetTable>. LoadTable() loads only the table; each asset loads when it is requested.
  • Asset table classes also get LoadEntries(), which loads the table and the assets of all its entries, so no asset lookup waits afterwards. Assets of a table whose Preload Asset Table metadata is No Preload are not loaded.
  • With UniTask Members there are also LoadTableAsync(CancellationToken) and, for asset tables, LoadEntriesAsync(CancellationToken), returning UniTask<StringTable> / UniTask<AssetTable>.
  • The table is loaded for the current locale. After a locale change, call it again to load the new locale's table.
  • If Localization is not configured, the task completes with null.
  • Turning the option on never renames existing members. A key named LoadTable or LoadEntries keeps its name, and the method gets a suffix (LoadTable_2). A table collection named Task, StringTable or AssetTable gets the Table class suffix.

UniTask

Install UniTask (com.cysharp.unitask 2.x) and enable UniTask Members to emit an awaitable variant next to every member:

public static string HelloWorld => LocalizedTables.GetString(TableName, "HelloWorld");

public static UniTask<string> HelloWorldAsync(CancellationToken cancellationToken = default)
    => LocalizedTablesUniTask.GetStringAsync(TableName, "HelloWorld", cancellationToken);
label.text = await Ui.HelloWorldAsync(this.GetCancellationTokenOnDestroy());
Sprite icon = await Icons.SwordAsync();
  • The async members never block on table loading, so they also work where synchronous loads are not supported (WebGL).
  • Smart string methods keep their parameters (await Ui.GreetingAsync(player, count)), and asset entries return UniTask<T>.
  • Cancelling stops the wait; Localization still finishes loading the table in the background.
  • Turning the option on never renames existing members. A key that already ends in Async keeps its name, and the generated variant gets a suffix (TitleAsync_2).
  • LocalizedString.GetLocalizedStringUniTask() awaits any LocalizedString, including Ref members.

Important

The API lives in the optional com.severnbli.localization-codegen.UniTask assembly, which compiles only when UniTask is installed as a package. If UniTask lives under Assets/, add the scripting define LOCALIZATION_CODEGEN_UNITASK. Without that assembly the option is skipped with a warning, because the generated code would not compile.

Settings

Open Project Settings > Localization Codegen, or Window > Localization Codegen for the standalone window. Settings are stored in ProjectSettings/LocalizationCodegenSettings.asset.

Setting Default Description
Namespace Localization Namespace of generated classes. Empty or whitespace means the global namespace.
Output Folder Assets/Generated/Localization Must be inside Assets. Changing it removes generated files from the old folder. Inside another .asmdef, you are offered to add the references the code needs.
String Tables on Generate classes for string table collections. Disabling deletes the matching files on the next run.
Asset Tables on Generate classes for asset table collections. Disabling deletes the matching files on the next run.
Regenerate On Changes on Automatic regeneration when table assets are saved (File > Save Project or Ctrl+S) and after external (VCS) changes.
Silently On Settings Change off Regenerate without asking when a setting that changes the generated code is edited. Off asks first. Needs Regenerate On Changes.
On Metadata Edit off Regenerate after every edit of the Smart Parameter Types metadata. Off regenerates when the table is saved. Needs Regenerate On Changes.
Generate Reference Members off Emit the nested Ref class.
XML Documentation off Add XML docs with the default locale text and smart string parameters.
Smart Strings off (upgraded) / Methods (new) Off, Methods or MethodsAndRefs.
Smart Parameter Types Object Object, Inferred or Mapping.
Naming Convention Keep Keep or PascalCase.
Key Separators empty Characters that create nested classes, e.g. /.
Load Table Method off Emit LoadTable() on every table class, and LoadEntries() on asset table classes, to load without blocking.
UniTask Members off Also emit …Async members returning UniTask. Requires UniTask.
Generate .asmdef off Write an assembly definition into the output folder, so the generated code gets its own assembly.
Fail CI On Smart String Mismatch off Make CheckBatch fail on locale placeholder mismatches.

The window also has Regenerate Now, Open Output Folder and Run Setup Wizard buttons, and lists the warnings of the last run.

CI / batch mode

# Regenerate and fail on any error
Unity -batchmode -nographics -projectPath . \
  -executeMethod Severnbli.LocalizationCodegen.Editor.CodeGenerator.GenerateBatch

# Verify that generated code is up to date (no files are written)
Unity -batchmode -nographics -projectPath . \
  -executeMethod Severnbli.LocalizationCodegen.Editor.CodeGenerator.CheckBatch

CheckBatch compares the generated files on disk with the tables, so it also catches generated files that were edited by hand. The same actions are available under Tools > Localization Codegen > Regenerate and Tools > Localization Codegen > Verify (Dry run). The setup wizard is never opened in batch mode.

For clean diffs, add this to .gitattributes:

*.g.cs text eol=lf

Good to know

  • Only files in the output folder whose first line is // <auto-generated by Localization Codegen> are created, overwritten or deleted. Don't edit generated files by hand.
  • A manifest in the project settings remembers the last output folder, so changing the folder or namespace does not leave duplicate types behind.
  • If the output folder is inside one of your assembly definitions (directly or through an .asmref), the generated code compiles into that assembly, which must reference com.severnbli.localization-codegen.Runtime and Unity.Localization (plus UniTask and com.severnbli.localization-codegen.UniTask for UniTask members). When you pick such a folder you are asked to Add References to that .asmdef for you, or to Use Separate .asmdef (Generate .asmdef). The Output section keeps showing which assembly the code compiles into, and generation warns while references are missing.
  • The synchronous members block until the table is loaded and are not supported by Addressables on WebGL. Use UniTask members, or LocalizedTables.GetStringAsync / GetAssetAsync, there.
  • If LocalizationSettings are missing at runtime, generated members return the table key (and log once) instead of throwing.
  • The generator is editor-only; generated C# files have no runtime dependency on the generator assembly.

License

MIT © Usevalad Buben

About

C# classes and properties generator from Unity Localization tables

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Contributors

Languages