diff --git a/CHANGELOG.md b/CHANGELOG.md
index facfebf..b930378 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -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` and the other
+ localized asset types have no `(table, entry)` constructor.
+
## [1.1.1] - 2026-10-24
### Fixed
diff --git a/Installer/Assets/Editor/Localization Codegen Installer/Installer.cs b/Installer/Assets/Editor/Localization Codegen Installer/Installer.cs
index 6605419..4f8fadf 100644
--- a/Installer/Assets/Editor/Localization Codegen Installer/Installer.cs
+++ b/Installer/Assets/Editor/Localization Codegen Installer/Installer.cs
@@ -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()
{
diff --git a/README.md b/README.md
index 593d64b..f4e5741 100644
--- a/README.md
+++ b/README.md
@@ -19,22 +19,34 @@
+
+
+
+
---
## 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;
@@ -42,10 +54,32 @@ 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` 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
@@ -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.
@@ -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"
}
}
```
@@ -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
+//
+// 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
@@ -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 { ["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` 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` 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 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`.
+- 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 `// ` 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
diff --git a/Unity-Package/Assets/root/CHANGELOG.md b/Unity-Package/Assets/root/CHANGELOG.md
index 0d92154..b930378 100644
--- a/Unity-Package/Assets/root/CHANGELOG.md
+++ b/Unity-Package/Assets/root/CHANGELOG.md
@@ -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` and the other
+ localized asset types have no `(table, entry)` constructor.
+
## [1.1.1] - 2026-10-24
### Fixed
@@ -66,4 +80,4 @@
### Added
- Initial release of the Unity package.
- Added core functionality for A, B, and C.
-- Included documentation and example scenes.
\ No newline at end of file
+- Included documentation and example scenes.
diff --git a/Unity-Package/Assets/root/Editor/CodeEmitter.cs b/Unity-Package/Assets/root/Editor/CodeEmitter.cs
index 43e9c90..913109c 100644
--- a/Unity-Package/Assets/root/Editor/CodeEmitter.cs
+++ b/Unity-Package/Assets/root/Editor/CodeEmitter.cs
@@ -14,6 +14,9 @@ internal static class CodeEmitter
const string AssetObject = "global::UnityEngine.Object";
const string LocalizedStringType = "global::UnityEngine.Localization.LocalizedString";
const string LocalizedAssetType = "global::UnityEngine.Localization.LocalizedAsset";
+ const string UniTaskType = "global::Cysharp.Threading.Tasks.UniTask";
+ const string CancellationTokenType = "global::System.Threading.CancellationToken";
+ const string CancellationTokenName = "cancellationToken";
/// Assigns deterministic, collision-free class names to every model.
public static void AssignClassNames(IList models, EmitOptions options)
@@ -116,6 +119,7 @@ sealed class Scope
public readonly List Entries = new List();
public readonly Dictionary RawMemberNames = new Dictionary();
public readonly Dictionary MemberNames = new Dictionary();
+ public readonly Dictionary AsyncMemberNames = new Dictionary();
public readonly HashSet MemberUsed = new HashSet(StringComparer.Ordinal);
}
@@ -209,6 +213,20 @@ static void AssignMemberNames(Scope scope, EmitOptions options)
scope.MemberNames[entry] = CodegenText.Unique(pair.Key, scope.MemberUsed);
}
+ // Async names are claimed after every key's own name, so adding UniTask members never renames an
+ // existing member. A key that already ends in "Async" pushes the generated variant to a suffix.
+ if (options.UniTask)
+ {
+ var byId = scope.Entries
+ .OrderBy(e => e.Id)
+ .ThenBy(e => e.Key, StringComparer.Ordinal);
+ foreach (var entry in byId)
+ {
+ scope.AsyncMemberNames[entry] =
+ CodegenText.Unique(scope.MemberNames[entry].TrimStart('@') + "Async", scope.MemberUsed);
+ }
+ }
+
foreach (var child in scope.Children)
AssignMemberNames(child, options);
}
@@ -240,6 +258,13 @@ static void EmitScope(StringBuilder sb, Scope scope, TableModel model, EmitOptio
{
sb.Append('\n');
EmitEntry(sb, entry, scope.MemberNames[entry], options, level + 1);
+
+ string asyncName;
+ if (scope.AsyncMemberNames.TryGetValue(entry, out asyncName))
+ {
+ sb.Append('\n');
+ EmitAsyncEntry(sb, entry, asyncName, options, level + 1);
+ }
}
if (isRoot && options.Refs)
@@ -294,6 +319,55 @@ static void EmitEntry(StringBuilder sb, EntryModel entry, string name, EmitOptio
static bool IsAssetEntry(EntryModel entry) => entry.AssetTypeName != null;
+ /// Emits the UniTask variant of an entry, mirroring the parameters of its synchronous member.
+ static void EmitAsyncEntry(StringBuilder sb, EntryModel entry, string name, EmitOptions options, int level)
+ {
+ if (options.XmlDocs && !string.IsNullOrEmpty(entry.Preview))
+ EmitSummary(sb, entry.Preview, level);
+
+ var runtime = EmitOptions.UniTaskRuntimeTypeName;
+ if (IsAssetEntry(entry))
+ {
+ var type = string.IsNullOrEmpty(entry.AssetTypeName) ? AssetObject : entry.AssetTypeName;
+ sb.Append(Indent(level)).Append("public static ").Append(UniTaskType).Append('<').Append(type).Append("> ")
+ .Append(name).Append('(').Append(CancellationTokenType).Append(' ').Append(CancellationTokenName)
+ .Append(" = default)\n");
+ sb.Append(Indent(level)).Append(" => ").Append(runtime).Append(".GetAssetAsync<").Append(type)
+ .Append(">(TableName, ").Append(CodegenText.Literal(entry.Key)).Append(", ")
+ .Append(CancellationTokenName).Append(");\n");
+ return;
+ }
+
+ var withParams = options.SmartStrings != SmartStringMode.Off && entry.Params.Count > 0;
+ var positional = withParams
+ ? entry.Params.Where(p => p.IsPositional).OrderBy(p => p.Index).ToList()
+ : new List();
+ var named = withParams
+ ? entry.Params.Where(p => !p.IsPositional).OrderBy(p => p.SourceName, StringComparer.Ordinal).ToList()
+ : new List();
+
+ // A smart string variable may itself be called cancellationToken.
+ var parameterNames = new HashSet(entry.Params.Select(p => p.ClrName.TrimStart('@')), StringComparer.Ordinal);
+ var tokenName = withParams ? CodegenText.Unique(CancellationTokenName, parameterNames) : CancellationTokenName;
+
+ if (withParams)
+ {
+ EmitParameterDocs(sb, positional, named, level);
+ sb.Append(Indent(level)).Append("/// Stops waiting for the table to load.\n");
+ }
+
+ var parameters = ParameterList(positional, named);
+ sb.Append(Indent(level)).Append("public static ").Append(UniTaskType).Append(" ").Append(name).Append('(')
+ .Append(parameters).Append(parameters.Length > 0 ? ", " : "")
+ .Append(CancellationTokenType).Append(' ').Append(tokenName).Append(" = default)\n");
+ sb.Append(Indent(level)).Append(" => ").Append(runtime).Append(".GetStringAsync(TableName, ")
+ .Append(CodegenText.Literal(entry.Key)).Append(", ");
+ if (withParams)
+ sb.Append(PositionalArray(positional)).Append(", ").Append(NamedDictionary(named)).Append(", ");
+ sb.Append(tokenName).Append(");\n");
+ }
+
static void EmitRefClass(StringBuilder sb, TableModel model, EmitOptions options, int level)
{
var strict = !string.IsNullOrEmpty(options.KeySeparators);
@@ -347,10 +421,12 @@ static void EmitRefClass(StringBuilder sb, TableModel model, EmitOptions options
}
else
{
+ // Unlike LocalizedString, LocalizedAsset types only have a parameterless constructor.
var type = string.IsNullOrEmpty(entry.AssetTypeName) ? AssetObject : entry.AssetTypeName;
sb.Append(Indent(level + 1)).Append("public static ").Append(GetLocalizedAssetType(type)).Append(' ')
.Append(name).Append(" => new ").Append(GetLocalizedAssetType(type))
- .Append("(TableName, ").Append(CodegenText.Literal(entry.Key)).Append(");\n");
+ .Append(" { TableReference = TableName, TableEntryReference = ")
+ .Append(CodegenText.Literal(entry.Key)).Append(" };\n");
}
}
diff --git a/Unity-Package/Assets/root/Editor/CodeGenerator.cs b/Unity-Package/Assets/root/Editor/CodeGenerator.cs
index 5fef534..f85577f 100644
--- a/Unity-Package/Assets/root/Editor/CodeGenerator.cs
+++ b/Unity-Package/Assets/root/Editor/CodeGenerator.cs
@@ -97,6 +97,9 @@ public static GenerateResult Run(GenerateOptions options)
try
{
var emitOptions = BuildEmitOptions(settings);
+ if (settings.GenerateUniTask && !emitOptions.UniTask)
+ result.Warnings.Add(UniTaskSupport.MissingMessage);
+
var reader = new TableReader(emitOptions);
var read = reader.Read(settings.GenerateStringTables, settings.GenerateAssetTables);
result.Warnings.AddRange(read.Warnings);
@@ -284,7 +287,9 @@ static EmitOptions BuildEmitOptions(CodegenSettings settings)
Naming = settings.Naming,
KeySeparators = settings.KeySeparators,
SmartParamTypes = settings.SmartParamTypes,
- GenerateAsmdef = settings.GenerateAsmdef
+ GenerateAsmdef = settings.GenerateAsmdef,
+ // Generated code must compile, so the option only takes effect when the add-on is compiled.
+ UniTask = settings.GenerateUniTask && UniTaskSupport.IsAvailable
};
}
@@ -466,7 +471,7 @@ static string WriteAsmdefIfNeeded(
return fullPath;
}
- static string BuildAsmdefContent(EmitOptions options, List models, out string baseName)
+ internal static string BuildAsmdefContent(EmitOptions options, List models, out string baseName)
{
baseName = string.IsNullOrEmpty(options.Namespace)
? "LocalizationCodegen.Generated"
@@ -478,6 +483,12 @@ static string BuildAsmdefContent(EmitOptions options, List models, o
"Unity.Localization"
};
+ if (options.UniTask)
+ {
+ references.Add(UniTaskSupport.RuntimeAssemblyName);
+ references.Add(UniTaskSupport.UniTaskAssemblyName);
+ }
+
foreach (var model in models)
foreach (var assembly in model.AssetAssemblies)
references.Add(assembly);
diff --git a/Unity-Package/Assets/root/Editor/CodegenModel.cs b/Unity-Package/Assets/root/Editor/CodegenModel.cs
index 1d0ce84..2a2d710 100644
--- a/Unity-Package/Assets/root/Editor/CodegenModel.cs
+++ b/Unity-Package/Assets/root/Editor/CodegenModel.cs
@@ -74,6 +74,7 @@ internal sealed class EmitOptions
{
public const string DefaultRuntimeAlias = "__LT";
public const string RuntimeTypeName = "global::Severnbli.LocalizationCodegen.LocalizedTables";
+ public const string UniTaskRuntimeTypeName = "global::Severnbli.LocalizationCodegen.LocalizedTablesUniTask";
/// Normalized namespace, or for the global namespace.
public string Namespace;
@@ -90,10 +91,14 @@ internal sealed class EmitOptions
/// When true, an asmdef is generated and unreferenced player assemblies may be used.
public bool GenerateAsmdef;
+ /// When true, every member also gets a UniTask-returning ...Async variant.
+ public bool UniTask;
+
/// Stable signature of every option that can change output.
public string Signature()
{
- return string.Join("|", new[]
+ // UniTask is appended only when enabled, so existing hashes (and files) stay valid after upgrading.
+ return (UniTask ? "unitask|" : "") + string.Join("|", new[]
{
Namespace ?? "",
UseRuntimeAlias ? "alias" : "noalias",
diff --git a/Unity-Package/Assets/root/Editor/CodegenSettings.cs b/Unity-Package/Assets/root/Editor/CodegenSettings.cs
index 819227e..0a4b6e4 100644
--- a/Unity-Package/Assets/root/Editor/CodegenSettings.cs
+++ b/Unity-Package/Assets/root/Editor/CodegenSettings.cs
@@ -38,6 +38,9 @@ public sealed class CodegenSettings : ScriptableSingleton
[SerializeField] private bool generateAsmdef;
[SerializeField] private bool failOnSmartStringMismatch;
+ // Options introduced in 1.2.0. Off by default, so no migration is needed.
+ [SerializeField] private bool generateUniTask;
+
public bool SetupCompleted { get => setupCompleted; set => setupCompleted = value; }
public string OutputFolder { get => outputFolder; set => outputFolder = value; }
public string Namespace { get => generatedNamespace; set => generatedNamespace = value; }
@@ -56,6 +59,7 @@ public sealed class CodegenSettings : ScriptableSingleton
public bool GenerateXmlDocs { get => generateXmlDocs; set => generateXmlDocs = value; }
public bool GenerateAsmdef { get => generateAsmdef; set => generateAsmdef = value; }
public bool FailOnSmartStringMismatch { get => failOnSmartStringMismatch; set => failOnSmartStringMismatch = value; }
+ public bool GenerateUniTask { get => generateUniTask; set => generateUniTask = value; }
public SmartStringMode SmartStrings
{
diff --git a/Unity-Package/Assets/root/Editor/SettingsGui.cs b/Unity-Package/Assets/root/Editor/SettingsGui.cs
index 6279faf..6cbb3fd 100644
--- a/Unity-Package/Assets/root/Editor/SettingsGui.cs
+++ b/Unity-Package/Assets/root/Editor/SettingsGui.cs
@@ -97,6 +97,12 @@ public static bool Draw()
new GUIContent("Key Separators",
"Optional characters that create nested classes, e.g. '/' makes 'Menu/Start' become Menu.Start."),
s.KeySeparators);
+ s.GenerateUniTask = EditorGUILayout.Toggle(
+ new GUIContent("UniTask Members",
+ "Also emit ...Async members that return UniTask and accept a CancellationToken. Requires UniTask (com.cysharp.unitask)."),
+ s.GenerateUniTask);
+ if (s.GenerateUniTask && !UniTaskSupport.IsAvailable)
+ EditorGUILayout.HelpBox(UniTaskSupport.MissingMessage, MessageType.Warning);
EditorGUILayout.Space();
EditorGUILayout.LabelField("Advanced", EditorStyles.boldLabel);
diff --git a/Unity-Package/Assets/root/Editor/UniTaskSupport.cs b/Unity-Package/Assets/root/Editor/UniTaskSupport.cs
new file mode 100644
index 0000000..e4a8aba
--- /dev/null
+++ b/Unity-Package/Assets/root/Editor/UniTaskSupport.cs
@@ -0,0 +1,33 @@
+using System;
+
+namespace Severnbli.LocalizationCodegen.Editor
+{
+ /// Detects the optional UniTask runtime assembly that generated ...Async members call.
+ internal static class UniTaskSupport
+ {
+ public const string RuntimeAssemblyName = "com.severnbli.localization-codegen.UniTask";
+ public const string UniTaskAssemblyName = "UniTask";
+
+ public const string MissingMessage =
+ "UniTask members were not generated: the " + RuntimeAssemblyName + " assembly is not compiled. Install " +
+ "UniTask (com.cysharp.unitask) as a package, or define LOCALIZATION_CODEGEN_UNITASK when UniTask lives " +
+ "under Assets.";
+
+ ///
+ /// True when the add-on assembly is compiled. Its asmdef only compiles when UniTask is installed, so this
+ /// also means UniTask itself is available to generated code.
+ ///
+ public static bool IsAvailable
+ {
+ get
+ {
+ foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
+ {
+ if (string.Equals(assembly.GetName().Name, RuntimeAssemblyName, StringComparison.Ordinal))
+ return true;
+ }
+ return false;
+ }
+ }
+ }
+}
diff --git a/Unity-Package/Assets/root/Editor/UniTaskSupport.cs.meta b/Unity-Package/Assets/root/Editor/UniTaskSupport.cs.meta
new file mode 100644
index 0000000..38617bc
--- /dev/null
+++ b/Unity-Package/Assets/root/Editor/UniTaskSupport.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 4822f5c2af514e2385285946f69d7eb3
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Unity-Package/Assets/root/README.md b/Unity-Package/Assets/root/README.md
index ac3cc2e..f4e5741 100644
--- a/Unity-Package/Assets/root/README.md
+++ b/Unity-Package/Assets/root/README.md
@@ -19,22 +19,34 @@
+
+
+
+
+
---
## 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;
@@ -42,10 +54,32 @@ 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` 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
@@ -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.
@@ -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"
}
}
```
@@ -149,9 +184,12 @@ 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
@@ -170,8 +208,7 @@ namespace Localization
}
```
-The `__LT` alias is declared once per file. All other types (`LocalizedString`, asset types, `Dictionary<,>`)
-stay fully `global::`-qualified so user types cannot be shadowed.
+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:
@@ -181,7 +218,7 @@ 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;
@@ -189,7 +226,7 @@ Sprite icon = Icons.Sword;
### Naming rules
-Generated identifiers stay valid C#:
+Generated identifiers always stay valid C#:
- Invalid characters become `_`.
- Names starting with a digit get a `_` prefix.
@@ -199,9 +236,7 @@ Generated identifiers stay valid C#:
- 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.
+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
@@ -215,22 +250,21 @@ public static string Greeting(object arg0, int 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.
+- 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.
+- 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.
-Smart strings are opt-in. Upgraded projects default to `Off`; new projects default to `Methods` when the
-setup wizard completes.
+> [!NOTE]
+> Smart strings are opt-in. Upgraded projects default to `Off`; new projects default to `Methods` when the setup wizard completes.
### Reference members
-Enable **Generate Reference Members** to emit a nested `Ref` class:
+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` for asset tables), which knows which entry it points at and can follow locale changes:
```csharp
public static class Ref
@@ -240,13 +274,47 @@ public static class Ref
}
```
-Asset entries use `LocalizedSprite`, `LocalizedAudioClip`, `LocalizedAsset`, and the other built-in
-localized asset types when available.
+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` 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 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`.
+- 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`.
+Open **Project Settings > Localization Codegen**, or **Window > Localization Codegen** for the standalone window. Settings are stored in `ProjectSettings/LocalizationCodegenSettings.asset`.
| Setting | Default | Description |
|---|---|---|
@@ -256,15 +324,18 @@ window. Settings are stored in `ProjectSettings/LocalizationCodegenSettings.asse
| 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. |
+| 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
@@ -277,8 +348,7 @@ Unity -batchmode -nographics -projectPath . \
-executeMethod Severnbli.LocalizationCodegen.Editor.CodeGenerator.CheckBatch
```
-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.
+`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`:
@@ -290,11 +360,9 @@ For clean diffs, add this to `.gitattributes`:
- Only files in the output folder whose first line is `// ` 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 you move generated code into your own assembly definition, enable **Generate .asmdef** or reference `Unity.Localization` and `com.severnbli.localization-codegen.Runtime` manually.
-- Generated members use the synchronous localization APIs. They block until the table is loaded and are not
- supported by Addressables on WebGL. Use `LocalizedTables.GetStringAsync` / `GetAssetAsync` there.
-- If `LocalizationSettings` are missing at runtime, generated members return the table key (and log once)
- instead of throwing.
+- 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
diff --git a/Unity-Package/Assets/root/Runtime/AssemblyInfo.cs b/Unity-Package/Assets/root/Runtime/AssemblyInfo.cs
new file mode 100644
index 0000000..13e0ff4
--- /dev/null
+++ b/Unity-Package/Assets/root/Runtime/AssemblyInfo.cs
@@ -0,0 +1,3 @@
+using System.Runtime.CompilerServices;
+
+[assembly: InternalsVisibleTo("com.severnbli.localization-codegen.UniTask")]
diff --git a/Unity-Package/Assets/root/Runtime/AssemblyInfo.cs.meta b/Unity-Package/Assets/root/Runtime/AssemblyInfo.cs.meta
new file mode 100644
index 0000000..73c4817
--- /dev/null
+++ b/Unity-Package/Assets/root/Runtime/AssemblyInfo.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: a5ece4b0787a4796a66994287dcef5d2
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Unity-Package/Assets/root/Runtime/LocalizedTables.cs b/Unity-Package/Assets/root/Runtime/LocalizedTables.cs
index 8c64db0..2425750 100644
--- a/Unity-Package/Assets/root/Runtime/LocalizedTables.cs
+++ b/Unity-Package/Assets/root/Runtime/LocalizedTables.cs
@@ -22,7 +22,8 @@ public static class LocalizedTables
{
static bool s_WarnedMissingSettings;
- static bool HasSettings()
+ /// True when Localization is configured; logs one warning the first time it is not.
+ internal static bool HasSettings()
{
if (LocalizationSettings.HasSettings)
return true;
@@ -149,7 +150,7 @@ static object[] ToArray(IList