Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,19 @@
# Changelog

## [1.2.0] - 2026-10-24

### Added
- Optional UniTask support. Enable **UniTask Members** to emit a `...Async` method returning `UniTask` next to
every string and asset member, with a `CancellationToken` and the same smart string parameters.
- `LocalizedTablesUniTask` (`GetStringAsync`, `GetAssetAsync`) and the `LocalizedString.GetLocalizedStringUniTask()`
extension in the optional `com.severnbli.localization-codegen.UniTask` assembly, which compiles only when UniTask
(`com.cysharp.unitask`) is installed or `LOCALIZATION_CODEGEN_UNITASK` is defined.
- Editor tests compile the generated code with Unity's compiler, with warnings as errors.

### Fixed
- `Ref` members of asset table entries did not compile: `LocalizedSprite`, `LocalizedAsset<T>` and the other
localized asset types have no `(table, entry)` constructor.

## [1.1.1] - 2026-10-24

### Fixed
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ namespace Severnbli.LocalizationCodegen.Installer
public static partial class Installer
{
public const string PackageId = "com.severnbli.localization-codegen";
public const string Version = "1.1.1";
public const string Version = "1.2.0";

static Installer()
{
Expand Down
199 changes: 175 additions & 24 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,33 +19,67 @@
<a href="https://unity.com/">
<img alt="Unity 2021.3+" src="https://img.shields.io/badge/Unity-2021.3%2B-black?logo=unity" />
</a>
<a href="https://github.com/Cysharp/UniTask">
<img alt="UniTask optional" src="https://img.shields.io/badge/UniTask-optional-orange" />
</a>
<a href="LICENSE">
<img alt="MIT License" src="https://img.shields.io/badge/license-MIT-green" />
</a>
</p>

<p>
<a href="#quick-start">Quick start</a> •
<a href="#installation">Installation</a> •
<a href="#usage">Usage</a> •
<a href="#settings">Settings</a> •
<a href="#ci--batch-mode">CI</a> •
<a href="CHANGELOG.md">Changelog</a>
</p>

</div>

---

## Overview

Localization Codegen reads your [Unity Localization](https://docs.unity3d.com/Packages/com.unity.localization@1.5/manual/index.html) table collections and generates plain C# classes for them — one static class per collection, one property per key. No runtime reflection, no string lookups in your game code, and full autocomplete plus compile-time safety.
Localization Codegen reads your [Unity Localization](https://docs.unity3d.com/Packages/com.unity.localization@1.5/manual/index.html) 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.

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

// After
label.text = Ui.HelloWorld;
```

| Feature | Description |
|---|---|
| 🪄 **First-run wizard** | A setup wizard opens automatically after the package is first imported |
| 🧩 **Typed access** | One static class per string or asset table collection, one property per key |
| 🔁 **Automatic regeneration** | Regenerates when table collections, tables or entries change |
| 🛠️ **Editor tooling** | Dedicated window with manual regeneration and settings |
| 🧩 **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** | Debounced regeneration after table edits, 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](#option-1--openupm-recommended):

```bash
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:

```csharp
using Localization;

label.text = Ui.HelloWorld;
```

Edit your tables as usual — the classes regenerate on their own.

## Installation

Expand Down Expand Up @@ -78,6 +112,7 @@ The package is published on [OpenUPM](https://openupm.com/packages/com.severnbli

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.

<details>
Expand All @@ -99,7 +134,7 @@ Add the scoped registry and the dependency to `Packages/manifest.json`:
}
],
"dependencies": {
"com.severnbli.localization-codegen": "1.1.1"
"com.severnbli.localization-codegen": "1.2.0"
}
}
```
Expand Down Expand Up @@ -149,24 +184,32 @@ This variant bypasses Package Manager, so **versioning is manual**:
|---|---|
| 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](#unitask) |

## Usage

### Generated classes

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

```csharp
// <auto-generated by Localization Codegen>
// Table collection: Ui
using __LT = global::Severnbli.LocalizationCodegen.LocalizedTables;

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

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

The `__LT` alias is declared once per file. All other types (`LocalizedString`, asset types, `Dictionary<,>`) stay fully `global::`-qualified, so your own types can never shadow them.

Use it anywhere from your game code:

```csharp
Expand All @@ -175,44 +218,152 @@ using Localization;
label.text = Ui.HelloWorld;
```

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

```csharp
Sprite icon = Icons.Sword;
```

For strings with arguments or smart strings, use `LocalizedTables.GetString(Ui.TableName, "Key", args)`.

### Naming rules

Generated identifiers stay valid C#:
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.
- 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, …) 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:

```csharp
// "{0}, you have {count:plural:one item|{} items}"
public static string Greeting(object arg0, int count)
=> __LT.GetStringMixed(TableName, "Greeting", new object[] { arg0 },
new global::System.Collections.Generic.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`.
- 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.

### 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:

```csharp
public static class Ref
{
public static global::UnityEngine.Localization.LocalizedString HelloWorld
=> new global::UnityEngine.Localization.LocalizedString(TableName, "HelloWorld");
}
```

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

```csharp
// 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.

### UniTask

Install [UniTask](https://github.com/Cysharp/UniTask) (`com.cysharp.unitask` 2.x) and enable **UniTask Members** to emit an awaitable variant next to every member:

```csharp
public static string HelloWorld => __LT.GetString(TableName, "HelloWorld");

public static global::Cysharp.Threading.Tasks.UniTask<string> HelloWorldAsync(global::System.Threading.CancellationToken cancellationToken = default)
=> global::Severnbli.LocalizationCodegen.LocalizedTablesUniTask.GetStringAsync(TableName, "HelloWorld", cancellationToken);
```

```csharp
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 **Window > Localization Codegen**. Settings are stored in `ProjectSettings/LocalizationCodegenSettings.asset`.
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 (leave empty for the global namespace). |
| Output Folder | `Assets/Generated/Localization` | Must be inside `Assets`. |
| String Tables | on | Generate classes for string table collections. |
| Asset Tables | on | Generate classes for asset table collections. |
| Regenerate On Changes | on | Regenerate automatically when collections change. |
| 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. |
| 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 | Debounced automatic regeneration after table edits and external (VCS) changes. |
| Use Runtime Alias | on | Emit one `using __LT = ...;` instead of repeating the runtime type on every member. |
| Generate Reference Members | off | Emit the nested [`Ref` class](#reference-members). |
| 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` or `Inferred`. |
| Naming Convention | `Keep` | `Keep` or `PascalCase`. |
| Key Separators | empty | Characters that create nested classes, e.g. `/`. |
| UniTask Members | off | Also emit [`…Async` members](#unitask) returning `UniTask`. Requires UniTask. |
| Generate .asmdef | off | Write an assembly definition into the output folder. |
| 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

```bash
# 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.

Buttons:
For clean diffs, add this to `.gitattributes`:

- **Regenerate Now** — regenerate the code immediately.
- **Run Setup Wizard** — reopen the first-run wizard.
```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.
- If you move generated code into your own assembly definition, reference `Unity.Localization` and `com.severnbli.localization-codegen.Runtime`.
- A manifest in the project settings remembers the last output folder, so changing the folder or namespace does not leave duplicate types behind.
- If you move generated code into your own assembly definition, enable **Generate .asmdef**, or reference `Unity.Localization` and `com.severnbli.localization-codegen.Runtime` manually (plus `UniTask` and `com.severnbli.localization-codegen.UniTask` for UniTask members).
- The synchronous members block until the table is loaded and are not supported by Addressables on WebGL. Use [UniTask members](#unitask), 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

Expand Down
16 changes: 15 additions & 1 deletion Unity-Package/Assets/root/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,19 @@
# Changelog

## [1.2.0] - 2026-10-24

### Added
- Optional UniTask support. Enable **UniTask Members** to emit a `...Async` method returning `UniTask` next to
every string and asset member, with a `CancellationToken` and the same smart string parameters.
- `LocalizedTablesUniTask` (`GetStringAsync`, `GetAssetAsync`) and the `LocalizedString.GetLocalizedStringUniTask()`
extension in the optional `com.severnbli.localization-codegen.UniTask` assembly, which compiles only when UniTask
(`com.cysharp.unitask`) is installed or `LOCALIZATION_CODEGEN_UNITASK` is defined.
- Editor tests compile the generated code with Unity's compiler, with warnings as errors.

### Fixed
- `Ref` members of asset table entries did not compile: `LocalizedSprite`, `LocalizedAsset<T>` and the other
localized asset types have no `(table, entry)` constructor.

## [1.1.1] - 2026-10-24

### Fixed
Expand Down Expand Up @@ -66,4 +80,4 @@
### Added
- Initial release of the Unity package.
- Added core functionality for A, B, and C.
- Included documentation and example scenes.
- Included documentation and example scenes.
Loading
Loading