From 3269f97fd8562936895ce73242d965a6ad1a58d1 Mon Sep 17 00:00:00 2001 From: Usevalad Buben Date: Wed, 28 Oct 2026 09:53:56 +0300 Subject: [PATCH 1/2] Add opt-in LoadTable method to generated table classes Load Table Method emits LoadTable() on every table class, returning Task / Task, plus LoadTableAsync with UniTask Members. The runtime awaits the Localization operation through its completion callback, so it also works on WebGL. Off by default and claimed after key names, so existing output and members don't change. Bump version to 1.3.1. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 9 ++ .../Installer.cs | 2 +- README.md | 22 ++++- Unity-Package/Assets/root/CHANGELOG.md | 9 ++ .../Assets/root/Editor/CodeEmitter.cs | 50 +++++++++++ .../Assets/root/Editor/CodeGenerator.cs | 1 + .../Assets/root/Editor/CodegenModel.cs | 7 +- .../Assets/root/Editor/CodegenSettings.cs | 4 + .../Assets/root/Editor/SettingsGui.cs | 3 + Unity-Package/Assets/root/README.md | 22 ++++- .../Assets/root/Runtime/LocalizedTables.cs | 44 ++++++++++ .../Runtime/UniTask/LocalizedTablesUniTask.cs | 29 +++++++ .../Assets/root/Tests/Editor/EmitterTests.cs | 87 +++++++++++++++++++ .../Editor/GeneratedCodeCompilationTests.cs | 3 +- Unity-Package/Assets/root/package.json | 2 +- 15 files changed, 287 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e95ae17..7f3c8bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## [1.3.1] - 2026-10-28 + +### Added +- **Load Table Method**: every table class gets `LoadTable()`, which loads the table for the selected locale + without blocking and returns `Task` / `Task`. With **UniTask Members** there is also + `LoadTableAsync(CancellationToken)`. Off by default; turning it on never renames existing members. +- `LocalizedTables.LoadStringTable` / `LoadAssetTable` and `LocalizedTablesUniTask.LoadStringTableAsync` / + `LoadAssetTableAsync`. + ## [1.3.0] - 2026-10-28 ### Added diff --git a/Installer/Assets/Editor/Localization Codegen Installer/Installer.cs b/Installer/Assets/Editor/Localization Codegen Installer/Installer.cs index 503c293..b74a798 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.3.0"; + public const string Version = "1.3.1"; static Installer() { diff --git a/README.md b/README.md index 3d7198b..2e671f1 100644 --- a/README.md +++ b/README.md @@ -134,7 +134,7 @@ Add the scoped registry and the dependency to `Packages/manifest.json`: } ], "dependencies": { - "com.severnbli.localization-codegen": "1.3.0" + "com.severnbli.localization-codegen": "1.3.1" } } ``` @@ -318,6 +318,25 @@ 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. +### 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: + +```csharp +public static Task LoadTable() => LocalizedTables.LoadStringTable(TableName); +``` + +```csharp +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`. Only the table is loaded; each asset loads when it is requested. +- With [UniTask Members](#unitask) there is also `LoadTableAsync(CancellationToken)` returning `UniTask` / `UniTask`. +- 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` 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](https://github.com/Cysharp/UniTask) (`com.cysharp.unitask` 2.x) and enable **UniTask Members** to emit an awaitable variant next to every member: @@ -360,6 +379,7 @@ Open **Project Settings > Localization Codegen**, or **Window > Localization Cod | Smart Parameter Types | `Object` | `Object`, `Inferred` or [`Mapping`](#parameter-types). | | Naming Convention | `Keep` | `Keep` or `PascalCase`. | | Key Separators | empty | Characters that create nested classes, e.g. `/`. | +| Load Table Method | off | Emit [`LoadTable()`](#loading-a-table) on every table class to load the table without blocking. | | UniTask Members | off | Also emit [`…Async` members](#unitask) 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. | diff --git a/Unity-Package/Assets/root/CHANGELOG.md b/Unity-Package/Assets/root/CHANGELOG.md index e95ae17..7f3c8bd 100644 --- a/Unity-Package/Assets/root/CHANGELOG.md +++ b/Unity-Package/Assets/root/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## [1.3.1] - 2026-10-28 + +### Added +- **Load Table Method**: every table class gets `LoadTable()`, which loads the table for the selected locale + without blocking and returns `Task` / `Task`. With **UniTask Members** there is also + `LoadTableAsync(CancellationToken)`. Off by default; turning it on never renames existing members. +- `LocalizedTables.LoadStringTable` / `LoadAssetTable` and `LocalizedTablesUniTask.LoadStringTableAsync` / + `LoadAssetTableAsync`. + ## [1.3.0] - 2026-10-28 ### Added diff --git a/Unity-Package/Assets/root/Editor/CodeEmitter.cs b/Unity-Package/Assets/root/Editor/CodeEmitter.cs index 0bbb365..f377037 100644 --- a/Unity-Package/Assets/root/Editor/CodeEmitter.cs +++ b/Unity-Package/Assets/root/Editor/CodeEmitter.cs @@ -17,6 +17,9 @@ internal static class CodeEmitter const string UniTaskType = "Cysharp.Threading.Tasks.UniTask"; const string CancellationTokenType = "System.Threading.CancellationToken"; const string DictionaryType = "System.Collections.Generic.Dictionary"; + const string TaskType = "System.Threading.Tasks.Task"; + const string StringTableType = "UnityEngine.Localization.Tables.StringTable"; + const string AssetTableType = "UnityEngine.Localization.Tables.AssetTable"; const string CancellationTokenName = "cancellationToken"; /// @@ -31,6 +34,12 @@ internal static class CodeEmitter "UniTask", "CancellationToken", "Dictionary", "IEnumerable" }; + /// + /// Types only the LoadTable methods refer to. They are reserved only while the option is on, so turning + /// it on is the only thing that can rename a table class with one of these names. + /// + static readonly string[] s_LoadTableTypeNames = { "Task", "StringTable", "AssetTable" }; + /// Assigns deterministic, collision-free class names to every model. public static void AssignClassNames(IList models, EmitOptions options) { @@ -74,6 +83,8 @@ static HashSet ReservedClassNames(IList models, EmitOptions // Generated files refer to types by their simple names, which a table class must not hide. set.UnionWith(s_ReferencedTypeNames); + if (options.LoadTable) + set.UnionWith(s_LoadTableTypeNames); foreach (var model in models) { foreach (var entry in model.Entries) @@ -106,6 +117,14 @@ public static string Emit(TableModel model, EmitOptions options) root.ClassName = className; AssignMemberNames(root, options); + // Claimed after every key's name, so turning the option on never renames an existing member. + if (options.LoadTable) + { + root.LoadTableName = CodegenText.Unique("LoadTable", root.MemberUsed); + if (options.UniTask) + root.LoadTableAsyncName = CodegenText.Unique("LoadTableAsync", root.MemberUsed); + } + var hasNamespace = !string.IsNullOrEmpty(options.Namespace); var rootLevel = hasNamespace ? 1 : 0; @@ -159,6 +178,8 @@ sealed class Scope public readonly Dictionary MemberNames = new Dictionary(); public readonly Dictionary AsyncMemberNames = new Dictionary(); public readonly HashSet MemberUsed = new HashSet(StringComparer.Ordinal); + public string LoadTableName; + public string LoadTableAsyncName; } static Scope BuildScopeTree(TableModel model, EmitOptions options) @@ -286,6 +307,9 @@ static void EmitScope(StringBuilder sb, Scope scope, TableModel model, EmitOptio { sb.Append(Indent(level + 1)).Append("public const string TableName = ") .Append(CodegenText.Literal(model.Name)).Append(";\n"); + + if (scope.LoadTableName != null) + EmitLoadTable(sb, scope, model, options, types, level + 1); } var orderedEntries = scope.Entries @@ -416,6 +440,32 @@ static void EmitAsyncEntry(StringBuilder sb, EntryModel entry, string name, Emit sb.Append(tokenName).Append(");\n"); } + /// Emits LoadTable and, with UniTask, LoadTableAsync. + static void EmitLoadTable(StringBuilder sb, Scope scope, TableModel model, EmitOptions options, TypeNames types, int level) + { + var table = types.Name(model.IsAsset ? AssetTableType : StringTableType); + var kind = model.IsAsset ? "Asset" : "String"; + + sb.Append('\n'); + if (options.XmlDocs) + sb.Append(Indent(level)).Append("/// Loads the table for the selected locale without blocking.\n"); + sb.Append(Indent(level)).Append("public static ").Append(types.Name(TaskType)).Append('<').Append(table).Append("> ") + .Append(scope.LoadTableName).Append("() => ").Append(types.Name(EmitOptions.RuntimeTypeName)) + .Append(".Load").Append(kind).Append("Table(TableName);\n"); + + if (scope.LoadTableAsyncName == null) + return; + + sb.Append('\n'); + if (options.XmlDocs) + sb.Append(Indent(level)).Append("/// Loads the table for the selected locale without blocking.\n"); + sb.Append(Indent(level)).Append("public static ").Append(types.Name(UniTaskType)).Append('<').Append(table).Append("> ") + .Append(scope.LoadTableAsyncName).Append('(').Append(types.Name(CancellationTokenType)).Append(' ') + .Append(CancellationTokenName).Append(" = default)\n"); + sb.Append(Indent(level)).Append(" => ").Append(types.Name(EmitOptions.UniTaskRuntimeTypeName)) + .Append(".Load").Append(kind).Append("TableAsync(TableName, ").Append(CancellationTokenName).Append(");\n"); + } + static void EmitRefClass(StringBuilder sb, TableModel model, EmitOptions options, TypeNames types, int level) { var strict = !string.IsNullOrEmpty(options.KeySeparators); diff --git a/Unity-Package/Assets/root/Editor/CodeGenerator.cs b/Unity-Package/Assets/root/Editor/CodeGenerator.cs index 61b65ad..3df04a5 100644 --- a/Unity-Package/Assets/root/Editor/CodeGenerator.cs +++ b/Unity-Package/Assets/root/Editor/CodeGenerator.cs @@ -291,6 +291,7 @@ static EmitOptions BuildEmitOptions(CodegenSettings settings) GenerateAsmdef = settings.GenerateAsmdef, // Generated code must compile, so the option only takes effect when the add-on is compiled. UniTask = settings.GenerateUniTask && UniTaskSupport.IsAvailable, + LoadTable = settings.GenerateLoadTable, TypeExists = LoadedTypeExists }; } diff --git a/Unity-Package/Assets/root/Editor/CodegenModel.cs b/Unity-Package/Assets/root/Editor/CodegenModel.cs index c27be9e..d765b0d 100644 --- a/Unity-Package/Assets/root/Editor/CodegenModel.cs +++ b/Unity-Package/Assets/root/Editor/CodegenModel.cs @@ -98,6 +98,9 @@ internal sealed class EmitOptions /// When true, every member also gets a UniTask-returning ...Async variant. public bool UniTask; + /// When true, every table class gets a LoadTable method (and LoadTableAsync with UniTask). + public bool LoadTable; + /// /// Optional check whether a namespace (empty for the global namespace) contains a type with the given simple /// name. Generated files keep a type global:: qualified when its simple name could bind to another type. @@ -107,8 +110,8 @@ internal sealed class EmitOptions /// Stable signature of every option that can change output. public string Signature() { - // UniTask is appended only when enabled, so existing hashes (and files) stay valid after upgrading. - return (UniTask ? "unitask|" : "") + string.Join("|", new[] + // UniTask and LoadTable are added only when enabled, so existing hashes (and files) stay valid after upgrading. + return (LoadTable ? "loadtable|" : "") + (UniTask ? "unitask|" : "") + string.Join("|", new[] { Namespace ?? "", "usings", diff --git a/Unity-Package/Assets/root/Editor/CodegenSettings.cs b/Unity-Package/Assets/root/Editor/CodegenSettings.cs index ef5a58f..3432bd0 100644 --- a/Unity-Package/Assets/root/Editor/CodegenSettings.cs +++ b/Unity-Package/Assets/root/Editor/CodegenSettings.cs @@ -40,6 +40,9 @@ public sealed class CodegenSettings : ScriptableSingleton // Options introduced in 1.2.0. Off by default, so no migration is needed. [SerializeField] private bool generateUniTask; + // Options introduced in 1.3.1. Off by default, so no migration is needed. + [SerializeField] private bool generateLoadTable; + public bool SetupCompleted { get => setupCompleted; set => setupCompleted = value; } public string OutputFolder { get => outputFolder; set => outputFolder = value; } public string Namespace { get => generatedNamespace; set => generatedNamespace = value; } @@ -58,6 +61,7 @@ public sealed class CodegenSettings : ScriptableSingleton 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 bool GenerateLoadTable { get => generateLoadTable; set => generateLoadTable = value; } public SmartStringMode SmartStrings { diff --git a/Unity-Package/Assets/root/Editor/SettingsGui.cs b/Unity-Package/Assets/root/Editor/SettingsGui.cs index 9d68db2..064588f 100644 --- a/Unity-Package/Assets/root/Editor/SettingsGui.cs +++ b/Unity-Package/Assets/root/Editor/SettingsGui.cs @@ -42,6 +42,8 @@ internal static class Content "Emit a nested Ref class with LocalizedString / LocalizedAsset references that follow locale changes."); public static readonly GUIContent UniTask = new GUIContent("UniTask Members", "Also emit ...Async members that return UniTask and accept a CancellationToken. Requires UniTask (com.cysharp.unitask)."); + public static readonly GUIContent LoadTable = new GUIContent("Load Table Method", + "Emit LoadTable() on every table class to load the table without blocking (and LoadTableAsync with UniTask Members)."); public static readonly GUIContent XmlDocs = new GUIContent("XML Documentation", "Emit XML doc comments containing the default locale text."); @@ -360,6 +362,7 @@ static void DrawMembers(CodegenSettings s) s.GenerateReferences = value; } + s.GenerateLoadTable = EditorGUILayout.Toggle(Content.LoadTable, s.GenerateLoadTable); s.GenerateUniTask = EditorGUILayout.Toggle(Content.UniTask, s.GenerateUniTask); if (s.GenerateUniTask && !UniTaskSupport.IsAvailable) EditorGUILayout.HelpBox(UniTaskSupport.MissingMessage, MessageType.Warning); diff --git a/Unity-Package/Assets/root/README.md b/Unity-Package/Assets/root/README.md index 3d7198b..2e671f1 100644 --- a/Unity-Package/Assets/root/README.md +++ b/Unity-Package/Assets/root/README.md @@ -134,7 +134,7 @@ Add the scoped registry and the dependency to `Packages/manifest.json`: } ], "dependencies": { - "com.severnbli.localization-codegen": "1.3.0" + "com.severnbli.localization-codegen": "1.3.1" } } ``` @@ -318,6 +318,25 @@ 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. +### 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: + +```csharp +public static Task LoadTable() => LocalizedTables.LoadStringTable(TableName); +``` + +```csharp +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`. Only the table is loaded; each asset loads when it is requested. +- With [UniTask Members](#unitask) there is also `LoadTableAsync(CancellationToken)` returning `UniTask` / `UniTask`. +- 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` 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](https://github.com/Cysharp/UniTask) (`com.cysharp.unitask` 2.x) and enable **UniTask Members** to emit an awaitable variant next to every member: @@ -360,6 +379,7 @@ Open **Project Settings > Localization Codegen**, or **Window > Localization Cod | Smart Parameter Types | `Object` | `Object`, `Inferred` or [`Mapping`](#parameter-types). | | Naming Convention | `Keep` | `Keep` or `PascalCase`. | | Key Separators | empty | Characters that create nested classes, e.g. `/`. | +| Load Table Method | off | Emit [`LoadTable()`](#loading-a-table) on every table class to load the table without blocking. | | UniTask Members | off | Also emit [`…Async` members](#unitask) 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. | diff --git a/Unity-Package/Assets/root/Runtime/LocalizedTables.cs b/Unity-Package/Assets/root/Runtime/LocalizedTables.cs index 2425750..042ff6a 100644 --- a/Unity-Package/Assets/root/Runtime/LocalizedTables.cs +++ b/Unity-Package/Assets/root/Runtime/LocalizedTables.cs @@ -1,5 +1,6 @@ using System.Collections; using System.Collections.Generic; +using System.Threading.Tasks; using UnityEngine; using UnityEngine.Localization; using UnityEngine.Localization.Settings; @@ -142,6 +143,49 @@ public static AsyncOperationHandle GetAssetAsync(string table, string key) (TableReference)table, (TableEntryReference)key); } + /// + /// Loads a string table for the selected locale without blocking, so later lookups do not wait for it. + /// Completes with when Localization is not configured. + /// + public static Task LoadStringTable(string table) + { + if (!HasSettings()) + return Task.FromResult(null); + return ToTask(LocalizationSettings.StringDatabase.GetTableAsync(table)); + } + + /// + /// Loads an asset table for the selected locale without blocking. The assets of its entries are loaded + /// when they are requested. Completes with when Localization is not configured. + /// + public static Task LoadAssetTable(string table) + { + if (!HasSettings()) + return Task.FromResult(null); + return ToTask(LocalizationSettings.AssetDatabase.GetTableAsync(table)); + } + + /// + /// Awaits a Localization operation through its completion callback, which also works on WebGL. The result is + /// read inside the callback because Localization may release the operation right after it completes. + /// + static Task ToTask(AsyncOperationHandle handle) + { + if (!handle.IsValid()) + return Task.FromException(new System.InvalidOperationException("The localization operation is not valid.")); + + var source = new TaskCompletionSource(); + handle.Completed += completed => + { + if (completed.Status == AsyncOperationStatus.Succeeded) + source.TrySetResult(completed.Result); + else + source.TrySetException(completed.OperationException ?? new System.InvalidOperationException( + "The localization operation failed with status " + completed.Status + ".")); + }; + return source.Task; + } + static object[] ToArray(IList values) { var array = new object[values.Count]; diff --git a/Unity-Package/Assets/root/Runtime/UniTask/LocalizedTablesUniTask.cs b/Unity-Package/Assets/root/Runtime/UniTask/LocalizedTablesUniTask.cs index 33daa9d..e718b29 100644 --- a/Unity-Package/Assets/root/Runtime/UniTask/LocalizedTablesUniTask.cs +++ b/Unity-Package/Assets/root/Runtime/UniTask/LocalizedTablesUniTask.cs @@ -5,6 +5,7 @@ using UnityEngine.Localization; using UnityEngine.Localization.Settings; using UnityEngine.Localization.SmartFormat.PersistentVariables; +using UnityEngine.Localization.Tables; using UnityEngine.ResourceManagement.AsyncOperations; namespace Severnbli.LocalizationCodegen @@ -78,6 +79,34 @@ public static UniTask GetAssetAsync(string table, string key, Cancellation return ToUniTask(handle, cancellationToken); } + /// + /// Loads a string table for the selected locale without blocking, so later lookups do not wait for it. + /// Completes with when Localization is not configured. + /// + public static UniTask LoadStringTableAsync(string table, CancellationToken cancellationToken = default) + { + if (cancellationToken.IsCancellationRequested) + return UniTask.FromCanceled(cancellationToken); + if (!LocalizedTables.HasSettings()) + return UniTask.FromResult(null); + + return ToUniTask(LocalizationSettings.StringDatabase.GetTableAsync(table), cancellationToken); + } + + /// + /// Loads an asset table for the selected locale without blocking. The assets of its entries are loaded + /// when they are requested. Completes with when Localization is not configured. + /// + public static UniTask LoadAssetTableAsync(string table, CancellationToken cancellationToken = default) + { + if (cancellationToken.IsCancellationRequested) + return UniTask.FromCanceled(cancellationToken); + if (!LocalizedTables.HasSettings()) + return UniTask.FromResult(null); + + return ToUniTask(LocalizationSettings.AssetDatabase.GetTableAsync(table), cancellationToken); + } + /// /// Awaits a Localization operation. The result is read inside the completion callback because Localization /// releases the operation right after it completes. diff --git a/Unity-Package/Assets/root/Tests/Editor/EmitterTests.cs b/Unity-Package/Assets/root/Tests/Editor/EmitterTests.cs index c3ef2c7..a9b21be 100644 --- a/Unity-Package/Assets/root/Tests/Editor/EmitterTests.cs +++ b/Unity-Package/Assets/root/Tests/Editor/EmitterTests.cs @@ -579,5 +579,92 @@ public void KeySeparators_CreateNestedClasses() StringAssert.Contains("public static string Quit =>", output); StringAssert.Contains("public static string Title =>", output); } + + static EmitOptions LoadTableOptions(bool uniTask = false) + { + return new EmitOptions { Namespace = "Localization", LoadTable = true, UniTask = uniTask }; + } + + [Test] + public void LoadTable_IsOffByDefault() + { + var model = Model("Ui", false, (1L, "Title")); + var options = LegacyOptions(); + CodeEmitter.AssignClassNames(new[] { model }, options); + var output = CodeEmitter.Emit(model, options); + + StringAssert.DoesNotContain("LoadTable", output); + StringAssert.DoesNotContain("System.Threading.Tasks", output); + } + + [Test] + public void LoadTable_StringTable() + { + var model = Model("Ui", false, (1L, "Title")); + var options = LoadTableOptions(); + CodeEmitter.AssignClassNames(new[] { model }, options); + var output = CodeEmitter.Emit(model, options); + + StringAssert.Contains( + " public const string TableName = \"Ui\";\n" + + "\n" + + " public static Task LoadTable() => LocalizedTables.LoadStringTable(TableName);\n", + output); + StringAssert.Contains("using System.Threading.Tasks;\n", output); + StringAssert.Contains("using UnityEngine.Localization.Tables;\n", output); + StringAssert.DoesNotContain("LoadTableAsync", output); + } + + [Test] + public void LoadTable_AssetTable() + { + var model = Model("Ui", true, (1L, "Logo")); + var options = LoadTableOptions(); + CodeEmitter.AssignClassNames(new[] { model }, options); + var output = CodeEmitter.Emit(model, options); + + StringAssert.Contains( + "public static Task LoadTable() => LocalizedTables.LoadAssetTable(TableName);\n", output); + } + + [Test] + public void LoadTable_WithUniTask_EmitsAsyncVariant() + { + var model = Model("Ui", false, (1L, "Title")); + var options = LoadTableOptions(uniTask: true); + CodeEmitter.AssignClassNames(new[] { model }, options); + var output = CodeEmitter.Emit(model, options); + + StringAssert.Contains( + " public static UniTask LoadTableAsync(CancellationToken cancellationToken = default)\n" + + " => LocalizedTablesUniTask.LoadStringTableAsync(TableName, cancellationToken);\n", + output); + } + + [Test] + public void LoadTable_DoesNotRenameAKeyWithTheSameName() + { + var model = Model("Ui", false, (1L, "LoadTable"), (2L, "LoadTableAsync")); + var options = LoadTableOptions(uniTask: true); + CodeEmitter.AssignClassNames(new[] { model }, options); + var output = CodeEmitter.Emit(model, options); + + StringAssert.Contains("public static string LoadTable =>", output); + StringAssert.Contains("public static string LoadTableAsync =>", output); + StringAssert.Contains("public static Task LoadTable_2()", output); + StringAssert.Contains("public static UniTask LoadTableAsync_3(", output); + } + + [Test] + public void LoadTable_ReservesItsTypeNamesOnlyWhenOn() + { + var off = Model("Task", false, (1L, "Title")); + CodeEmitter.AssignClassNames(new[] { off }, LegacyOptions()); + Assert.AreEqual("Task", off.ClassName); + + var on = Model("Task", false, (1L, "Title")); + CodeEmitter.AssignClassNames(new[] { on }, LoadTableOptions()); + Assert.AreEqual("TaskTable", on.ClassName); + } } } diff --git a/Unity-Package/Assets/root/Tests/Editor/GeneratedCodeCompilationTests.cs b/Unity-Package/Assets/root/Tests/Editor/GeneratedCodeCompilationTests.cs index a194485..8ade489 100644 --- a/Unity-Package/Assets/root/Tests/Editor/GeneratedCodeCompilationTests.cs +++ b/Unity-Package/Assets/root/Tests/Editor/GeneratedCodeCompilationTests.cs @@ -159,7 +159,8 @@ static IEnumerable Variants(bool uniTask) SmartStrings = SmartStringMode.MethodsAndRefs, SmartParamTypes = SmartParamTypeMode.Inferred, KeySeparators = "/", - UniTask = uniTask + UniTask = uniTask, + LoadTable = true } }; diff --git a/Unity-Package/Assets/root/package.json b/Unity-Package/Assets/root/package.json index 65458fa..f884520 100644 --- a/Unity-Package/Assets/root/package.json +++ b/Unity-Package/Assets/root/package.json @@ -10,7 +10,7 @@ "Generation", "Code Generation" ], - "version": "1.3.0", + "version": "1.3.1", "unity": "2021.3", "description": "C# classes and properties generator from Unity Localization tables", "documentationUrl": "https://github.com/Severnbli/localization-codegen/blob/main/README.md", From 056b0861760accdc04a359d37e749cb134f6a27e Mon Sep 17 00:00:00 2001 From: Usevalad Buben Date: Wed, 28 Oct 2026 10:03:40 +0300 Subject: [PATCH 2/2] Add LoadEntries to asset table classes With Load Table Method on, asset table classes also get LoadEntries() (and LoadEntriesAsync with UniTask), which preloads the table and the assets of all its entries through PreloadTables. LoadTable stays table-only. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 7 +-- README.md | 9 ++-- Unity-Package/Assets/root/CHANGELOG.md | 7 +-- .../Assets/root/Editor/CodeEmitter.cs | 48 +++++++++++++++---- .../Assets/root/Editor/SettingsGui.cs | 2 +- Unity-Package/Assets/root/README.md | 9 ++-- .../Assets/root/Runtime/LocalizedTables.cs | 40 +++++++++++++++- .../Runtime/UniTask/LocalizedTablesUniTask.cs | 48 +++++++++++++++++++ .../Assets/root/Tests/Editor/EmitterTests.cs | 39 +++++++++++++++ 9 files changed, 182 insertions(+), 27 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7f3c8bd..bec9902 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,9 +5,10 @@ ### Added - **Load Table Method**: every table class gets `LoadTable()`, which loads the table for the selected locale without blocking and returns `Task` / `Task`. With **UniTask Members** there is also - `LoadTableAsync(CancellationToken)`. Off by default; turning it on never renames existing members. -- `LocalizedTables.LoadStringTable` / `LoadAssetTable` and `LocalizedTablesUniTask.LoadStringTableAsync` / - `LoadAssetTableAsync`. + `LoadTableAsync(CancellationToken)`. Asset table classes also get `LoadEntries()` / `LoadEntriesAsync`, which + load the table and the assets of all its entries. Off by default; turning it on never renames existing members. +- `LocalizedTables.LoadStringTable` / `LoadAssetTable` / `LoadAssetTableEntries` and + `LocalizedTablesUniTask.LoadStringTableAsync` / `LoadAssetTableAsync` / `LoadAssetTableEntriesAsync`. ## [1.3.0] - 2026-10-28 diff --git a/README.md b/README.md index 2e671f1..76c8662 100644 --- a/README.md +++ b/README.md @@ -331,11 +331,12 @@ 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`. Only the table is loaded; each asset loads when it is requested. -- With [UniTask Members](#unitask) there is also `LoadTableAsync(CancellationToken)` returning `UniTask` / `UniTask`. +- Asset table classes return `Task`. `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](#unitask) there are also `LoadTableAsync(CancellationToken)` and, for asset tables, `LoadEntriesAsync(CancellationToken)`, returning `UniTask` / `UniTask`. - 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` keeps its name, and the method gets a suffix (`LoadTable_2`). A table collection named `Task`, `StringTable` or `AssetTable` gets the `Table` class suffix. +- 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 @@ -379,7 +380,7 @@ Open **Project Settings > Localization Codegen**, or **Window > Localization Cod | Smart Parameter Types | `Object` | `Object`, `Inferred` or [`Mapping`](#parameter-types). | | Naming Convention | `Keep` | `Keep` or `PascalCase`. | | Key Separators | empty | Characters that create nested classes, e.g. `/`. | -| Load Table Method | off | Emit [`LoadTable()`](#loading-a-table) on every table class to load the table without blocking. | +| Load Table Method | off | Emit [`LoadTable()`](#loading-a-table) on every table class, and `LoadEntries()` on asset table classes, to load without blocking. | | UniTask Members | off | Also emit [`…Async` members](#unitask) 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. | diff --git a/Unity-Package/Assets/root/CHANGELOG.md b/Unity-Package/Assets/root/CHANGELOG.md index 7f3c8bd..bec9902 100644 --- a/Unity-Package/Assets/root/CHANGELOG.md +++ b/Unity-Package/Assets/root/CHANGELOG.md @@ -5,9 +5,10 @@ ### Added - **Load Table Method**: every table class gets `LoadTable()`, which loads the table for the selected locale without blocking and returns `Task` / `Task`. With **UniTask Members** there is also - `LoadTableAsync(CancellationToken)`. Off by default; turning it on never renames existing members. -- `LocalizedTables.LoadStringTable` / `LoadAssetTable` and `LocalizedTablesUniTask.LoadStringTableAsync` / - `LoadAssetTableAsync`. + `LoadTableAsync(CancellationToken)`. Asset table classes also get `LoadEntries()` / `LoadEntriesAsync`, which + load the table and the assets of all its entries. Off by default; turning it on never renames existing members. +- `LocalizedTables.LoadStringTable` / `LoadAssetTable` / `LoadAssetTableEntries` and + `LocalizedTablesUniTask.LoadStringTableAsync` / `LoadAssetTableAsync` / `LoadAssetTableEntriesAsync`. ## [1.3.0] - 2026-10-28 diff --git a/Unity-Package/Assets/root/Editor/CodeEmitter.cs b/Unity-Package/Assets/root/Editor/CodeEmitter.cs index f377037..fa7f592 100644 --- a/Unity-Package/Assets/root/Editor/CodeEmitter.cs +++ b/Unity-Package/Assets/root/Editor/CodeEmitter.cs @@ -121,8 +121,14 @@ public static string Emit(TableModel model, EmitOptions options) if (options.LoadTable) { root.LoadTableName = CodegenText.Unique("LoadTable", root.MemberUsed); + if (model.IsAsset) + root.LoadEntriesName = CodegenText.Unique("LoadEntries", root.MemberUsed); if (options.UniTask) + { root.LoadTableAsyncName = CodegenText.Unique("LoadTableAsync", root.MemberUsed); + if (model.IsAsset) + root.LoadEntriesAsyncName = CodegenText.Unique("LoadEntriesAsync", root.MemberUsed); + } } var hasNamespace = !string.IsNullOrEmpty(options.Namespace); @@ -180,6 +186,8 @@ sealed class Scope public readonly HashSet MemberUsed = new HashSet(StringComparer.Ordinal); public string LoadTableName; public string LoadTableAsyncName; + public string LoadEntriesName; + public string LoadEntriesAsyncName; } static Scope BuildScopeTree(TableModel model, EmitOptions options) @@ -440,30 +448,50 @@ static void EmitAsyncEntry(StringBuilder sb, EntryModel entry, string name, Emit sb.Append(tokenName).Append(");\n"); } - /// Emits LoadTable and, with UniTask, LoadTableAsync. + /// + /// Emits LoadTable, LoadEntries for asset tables, and their UniTask variants. + /// static void EmitLoadTable(StringBuilder sb, Scope scope, TableModel model, EmitOptions options, TypeNames types, int level) { var table = types.Name(model.IsAsset ? AssetTableType : StringTableType); var kind = model.IsAsset ? "Asset" : "String"; + const string tableDoc = "Loads the table for the selected locale without blocking."; + const string entriesDoc = "Loads the table and the assets of all its entries for the selected locale without blocking."; + + EmitLoadMethod(sb, scope.LoadTableName, "Load" + kind + "Table", table, tableDoc, options, types, level); + if (scope.LoadEntriesName != null) + EmitLoadMethod(sb, scope.LoadEntriesName, "LoadAssetTableEntries", table, entriesDoc, options, types, level); + + if (scope.LoadTableAsyncName != null) + EmitLoadAsyncMethod(sb, scope.LoadTableAsyncName, "Load" + kind + "TableAsync", table, tableDoc, options, types, level); + if (scope.LoadEntriesAsyncName != null) + EmitLoadAsyncMethod(sb, scope.LoadEntriesAsyncName, "LoadAssetTableEntriesAsync", table, entriesDoc, options, types, level); + } + static void EmitLoadMethod( + StringBuilder sb, string name, string runtimeMethod, string table, string doc, + EmitOptions options, TypeNames types, int level) + { sb.Append('\n'); if (options.XmlDocs) - sb.Append(Indent(level)).Append("/// Loads the table for the selected locale without blocking.\n"); + sb.Append(Indent(level)).Append("/// ").Append(doc).Append("\n"); sb.Append(Indent(level)).Append("public static ").Append(types.Name(TaskType)).Append('<').Append(table).Append("> ") - .Append(scope.LoadTableName).Append("() => ").Append(types.Name(EmitOptions.RuntimeTypeName)) - .Append(".Load").Append(kind).Append("Table(TableName);\n"); - - if (scope.LoadTableAsyncName == null) - return; + .Append(name).Append("() => ").Append(types.Name(EmitOptions.RuntimeTypeName)) + .Append('.').Append(runtimeMethod).Append("(TableName);\n"); + } + static void EmitLoadAsyncMethod( + StringBuilder sb, string name, string runtimeMethod, string table, string doc, + EmitOptions options, TypeNames types, int level) + { sb.Append('\n'); if (options.XmlDocs) - sb.Append(Indent(level)).Append("/// Loads the table for the selected locale without blocking.\n"); + sb.Append(Indent(level)).Append("/// ").Append(doc).Append("\n"); sb.Append(Indent(level)).Append("public static ").Append(types.Name(UniTaskType)).Append('<').Append(table).Append("> ") - .Append(scope.LoadTableAsyncName).Append('(').Append(types.Name(CancellationTokenType)).Append(' ') + .Append(name).Append('(').Append(types.Name(CancellationTokenType)).Append(' ') .Append(CancellationTokenName).Append(" = default)\n"); sb.Append(Indent(level)).Append(" => ").Append(types.Name(EmitOptions.UniTaskRuntimeTypeName)) - .Append(".Load").Append(kind).Append("TableAsync(TableName, ").Append(CancellationTokenName).Append(");\n"); + .Append('.').Append(runtimeMethod).Append("(TableName, ").Append(CancellationTokenName).Append(");\n"); } static void EmitRefClass(StringBuilder sb, TableModel model, EmitOptions options, TypeNames types, int level) diff --git a/Unity-Package/Assets/root/Editor/SettingsGui.cs b/Unity-Package/Assets/root/Editor/SettingsGui.cs index 064588f..3cb6760 100644 --- a/Unity-Package/Assets/root/Editor/SettingsGui.cs +++ b/Unity-Package/Assets/root/Editor/SettingsGui.cs @@ -43,7 +43,7 @@ internal static class Content public static readonly GUIContent UniTask = new GUIContent("UniTask Members", "Also emit ...Async members that return UniTask and accept a CancellationToken. Requires UniTask (com.cysharp.unitask)."); public static readonly GUIContent LoadTable = new GUIContent("Load Table Method", - "Emit LoadTable() on every table class to load the table without blocking (and LoadTableAsync with UniTask Members)."); + "Emit LoadTable() on every table class and LoadEntries() on asset table classes to load without blocking (and ...Async variants with UniTask Members)."); public static readonly GUIContent XmlDocs = new GUIContent("XML Documentation", "Emit XML doc comments containing the default locale text."); diff --git a/Unity-Package/Assets/root/README.md b/Unity-Package/Assets/root/README.md index 2e671f1..76c8662 100644 --- a/Unity-Package/Assets/root/README.md +++ b/Unity-Package/Assets/root/README.md @@ -331,11 +331,12 @@ 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`. Only the table is loaded; each asset loads when it is requested. -- With [UniTask Members](#unitask) there is also `LoadTableAsync(CancellationToken)` returning `UniTask` / `UniTask`. +- Asset table classes return `Task`. `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](#unitask) there are also `LoadTableAsync(CancellationToken)` and, for asset tables, `LoadEntriesAsync(CancellationToken)`, returning `UniTask` / `UniTask`. - 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` keeps its name, and the method gets a suffix (`LoadTable_2`). A table collection named `Task`, `StringTable` or `AssetTable` gets the `Table` class suffix. +- 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 @@ -379,7 +380,7 @@ Open **Project Settings > Localization Codegen**, or **Window > Localization Cod | Smart Parameter Types | `Object` | `Object`, `Inferred` or [`Mapping`](#parameter-types). | | Naming Convention | `Keep` | `Keep` or `PascalCase`. | | Key Separators | empty | Characters that create nested classes, e.g. `/`. | -| Load Table Method | off | Emit [`LoadTable()`](#loading-a-table) on every table class to load the table without blocking. | +| Load Table Method | off | Emit [`LoadTable()`](#loading-a-table) on every table class, and `LoadEntries()` on asset table classes, to load without blocking. | | UniTask Members | off | Also emit [`…Async` members](#unitask) 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. | diff --git a/Unity-Package/Assets/root/Runtime/LocalizedTables.cs b/Unity-Package/Assets/root/Runtime/LocalizedTables.cs index 042ff6a..42eaf7b 100644 --- a/Unity-Package/Assets/root/Runtime/LocalizedTables.cs +++ b/Unity-Package/Assets/root/Runtime/LocalizedTables.cs @@ -165,6 +165,20 @@ public static Task LoadAssetTable(string table) return ToTask(LocalizationSettings.AssetDatabase.GetTableAsync(table)); } + /// + /// Loads an asset table and the assets of all its entries for the selected locale without blocking, so later + /// lookups do not wait. A table whose Preload Asset Table metadata is No Preload loads without its assets. + /// Completes with when Localization is not configured. + /// + public static async Task LoadAssetTableEntries(string table) + { + if (!HasSettings()) + return null; + + await ToTask(LocalizationSettings.AssetDatabase.PreloadTables(table)); + return await LoadAssetTable(table); + } + /// /// Awaits a Localization operation through its completion callback, which also works on WebGL. The result is /// read inside the callback because Localization may release the operation right after it completes. @@ -180,12 +194,34 @@ static Task ToTask(AsyncOperationHandle handle) if (completed.Status == AsyncOperationStatus.Succeeded) source.TrySetResult(completed.Result); else - source.TrySetException(completed.OperationException ?? new System.InvalidOperationException( - "The localization operation failed with status " + completed.Status + ".")); + source.TrySetException(Failure(completed.Status, completed.OperationException)); }; return source.Task; } + /// Untyped variant of . + static Task ToTask(AsyncOperationHandle handle) + { + if (!handle.IsValid()) + return Task.FromException(new System.InvalidOperationException("The localization operation is not valid.")); + + var source = new TaskCompletionSource(); + handle.Completed += completed => + { + if (completed.Status == AsyncOperationStatus.Succeeded) + source.TrySetResult(true); + else + source.TrySetException(Failure(completed.Status, completed.OperationException)); + }; + return source.Task; + } + + static System.Exception Failure(AsyncOperationStatus status, System.Exception exception) + { + return exception ?? new System.InvalidOperationException( + "The localization operation failed with status " + status + "."); + } + static object[] ToArray(IList values) { var array = new object[values.Count]; diff --git a/Unity-Package/Assets/root/Runtime/UniTask/LocalizedTablesUniTask.cs b/Unity-Package/Assets/root/Runtime/UniTask/LocalizedTablesUniTask.cs index e718b29..9a7014e 100644 --- a/Unity-Package/Assets/root/Runtime/UniTask/LocalizedTablesUniTask.cs +++ b/Unity-Package/Assets/root/Runtime/UniTask/LocalizedTablesUniTask.cs @@ -107,6 +107,54 @@ public static UniTask LoadAssetTableAsync(string table, Cancellation return ToUniTask(LocalizationSettings.AssetDatabase.GetTableAsync(table), cancellationToken); } + /// + /// Loads an asset table and the assets of all its entries for the selected locale without blocking, so later + /// lookups do not wait. A table whose Preload Asset Table metadata is No Preload loads without its assets. + /// Completes with when Localization is not configured. + /// + public static async UniTask LoadAssetTableEntriesAsync( + string table, + CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + if (!LocalizedTables.HasSettings()) + return null; + + await ToUniTask(LocalizationSettings.AssetDatabase.PreloadTables(table), cancellationToken); + return await LoadAssetTableAsync(table, cancellationToken); + } + + /// Untyped variant of . + static UniTask ToUniTask(AsyncOperationHandle handle, CancellationToken cancellationToken) + { + if (!handle.IsValid()) + return UniTask.FromException(new InvalidOperationException("The localization operation is not valid.")); + if (handle.IsDone) + { + return handle.Status == AsyncOperationStatus.Succeeded + ? UniTask.CompletedTask + : UniTask.FromException(handle.OperationException ?? new InvalidOperationException( + "The localization operation failed with status " + handle.Status + ".")); + } + + var source = new UniTaskCompletionSource(); + var registration = cancellationToken.CanBeCanceled + ? cancellationToken.RegisterWithoutCaptureExecutionContext(() => source.TrySetCanceled(cancellationToken)) + : default; + + handle.Completed += completed => + { + registration.Dispose(); + if (completed.Status == AsyncOperationStatus.Succeeded) + source.TrySetResult(); + else + source.TrySetException(completed.OperationException ?? new InvalidOperationException( + "The localization operation failed with status " + completed.Status + ".")); + }; + + return source.Task; + } + /// /// Awaits a Localization operation. The result is read inside the completion callback because Localization /// releases the operation right after it completes. diff --git a/Unity-Package/Assets/root/Tests/Editor/EmitterTests.cs b/Unity-Package/Assets/root/Tests/Editor/EmitterTests.cs index a9b21be..2990520 100644 --- a/Unity-Package/Assets/root/Tests/Editor/EmitterTests.cs +++ b/Unity-Package/Assets/root/Tests/Editor/EmitterTests.cs @@ -625,6 +625,45 @@ public void LoadTable_AssetTable() StringAssert.Contains( "public static Task LoadTable() => LocalizedTables.LoadAssetTable(TableName);\n", output); + StringAssert.Contains( + "public static Task LoadEntries() => LocalizedTables.LoadAssetTableEntries(TableName);\n", + output); + } + + [Test] + public void LoadEntries_OnlyOnAssetTables() + { + var model = Model("Ui", false, (1L, "Title")); + var options = LoadTableOptions(uniTask: true); + CodeEmitter.AssignClassNames(new[] { model }, options); + + StringAssert.DoesNotContain("LoadEntries", CodeEmitter.Emit(model, options)); + } + + [Test] + public void LoadEntries_WithUniTask_EmitsAsyncVariant() + { + var model = Model("Ui", true, (1L, "Logo")); + var options = LoadTableOptions(uniTask: true); + CodeEmitter.AssignClassNames(new[] { model }, options); + var output = CodeEmitter.Emit(model, options); + + StringAssert.Contains( + " public static UniTask LoadEntriesAsync(CancellationToken cancellationToken = default)\n" + + " => LocalizedTablesUniTask.LoadAssetTableEntriesAsync(TableName, cancellationToken);\n", + output); + } + + [Test] + public void LoadEntries_DoesNotRenameAKeyWithTheSameName() + { + var model = Model("Ui", true, (1L, "LoadEntries")); + var options = LoadTableOptions(); + CodeEmitter.AssignClassNames(new[] { model }, options); + var output = CodeEmitter.Emit(model, options); + + StringAssert.Contains(" LoadEntries => LocalizedTables.GetAsset<", output); + StringAssert.Contains("public static Task LoadEntries_2()", output); } [Test]