t1k:unity:base:userdata-migrate
| Field | Value |
|---|---|
| Module | base |
| Version | 5.116.6 |
| Effort | low |
| Tools | — |
Keywords: json to memorypack, JsonSerializer, LD- prefix, legacy save, memorypack migration, migrate userdata, MigrateLegacyJsonToMemoryPack, preserve saves, userdata migration
How to invoke
Section titled “How to invoke”/t1k:unity:base:userdata-migrateMigrate UserData → MemoryPack
Section titled “Migrate UserData → MemoryPack”Port a Unity save model from legacy Newtonsoft-JSON persistence (stored in PlayerPrefs at key LD-{TypeName}) to MemoryPack binary serialization, preserving existing player saves via a one-time migration shim in UserDataManager.LoadAsync.
Scope: this is the migration procedure. The authoritative steady-state MemoryPack model rules (attributes,
UserDataManagerAPI, serializer selection, gotchas) live int1k-unity-base-userdata-memorypack— load it alongside this skill. When the two disagree, that skill wins.
This skill applies to one model or fifty. The full step-by-step (Search / Action / Verify per step) is in references/migration-playbook.md — read it before touching code.
When to use
Section titled “When to use”- An
IWritableDatamodel has no[MemoryPackable]and is still persisted as JSON. - You need a custom
MemoryPackFormatter<T>for a member type MemoryPack can’t serialize natively (e.g. R3ReactiveProperty<T>). - You need to wire (or verify) the one-time legacy
LD-{TypeName}JSON → MemoryPack conversion so existing installs don’t lose their saves.
When NOT to use
Section titled “When NOT to use”- Authoring a brand-new save model (already
[MemoryPackable]) → uset1k-unity-base-userdata-memorypack. - Migrating static CSV config → that is a blueprint concern (
t1k-unity-base-blueprint-migrate), not save data. - Editing a model shipped inside a submodule/package (
Packages/com.gdk.core,com.theone.data) — read-only from the consumer; PR the owning repo.
Mental model — legacy → current
Section titled “Mental model — legacy → current”| Concern | Legacy (Newtonsoft-JSON) | Current (MemoryPack) |
|---|---|---|
| Model class | class Foo : IWritableData | [MemoryPackable(GenerateType.VersionTolerant)] sealed partial class Foo : IWritableData |
| Per-member tag | none (JSON binds by name) | [MemoryPackOrder(n)] sequential from 0 |
| Computed member | implicitly skipped | [MemoryPackIgnore] (explicit — else generator error) |
| Storage key | "LD-" + type.Name (KeyPrefix) | type.GetKey() ([Key] value, else type name) |
| Storage backend | PlayerPrefsTextDataStorage (string) | PlayerPrefsBinaryDataStorage (byte[]) |
| Serializer selection | always JSON | [MemoryPackable] present → MemoryPack; else JSON |
| Version tolerance | JSON-lenient | GenerateType.VersionTolerant (no schemaVersion field) |
| Editor tooling attr | [OdinSerialize] | [OdinSerialize] — kept unchanged |
Key consequence: MemoryPack only activates when [MemoryPackable] is present (MemoryPackSerializer.CanSerialize gates on it). Annotating the models and adding the migration shim must land together — otherwise the app silently keeps writing JSON.
The three core moves
Section titled “The three core moves”1. Annotate the model (playbook §1)
Section titled “1. Annotate the model (playbook §1)”// beforeinternal sealed class FooLocalData : IWritableData{ [OdinSerialize] public HashSet<string> Completed { get; set; } = new();}
// after[MemoryPackable(GenerateType.VersionTolerant)]internal sealed partial class FooLocalData : IWritableData{ [MemoryPackOrder(0)] [OdinSerialize] public HashSet<string> Completed { get; set; } = new();}Add [MemoryPackable(GenerateType.VersionTolerant)], make the class partial, add [MemoryPackOrder(n)] sequentially per persisted member, [MemoryPackIgnore] on computed/get-only members. Leave [OdinSerialize] and [JsonProperty]/[JsonConstructor] untouched ([JsonProperty] is still used by the cloud-JSON path). Do the same for every nested DTO the model references.
2. Custom formatter for non-native member types (playbook §2)
Section titled “2. Custom formatter for non-native member types (playbook §2)”For a member type MemoryPack can’t serialize (e.g. ReactiveProperty<T>): mark it [MemoryPackAllowSerialize], write a MemoryPackFormatter<T>, and register it in both runtime ([RuntimeInitializeOnLoadMethod(BeforeSceneLoad)]) and editor ([UnityEditor.InitializeOnLoadMethod]) — the editor UserData tool deserializes in edit mode where the runtime hook never fires.
3. One-time JSON → MemoryPack migration shim (playbook §3)
Section titled “3. One-time JSON → MemoryPack migration shim (playbook §3)”In UserDataManager.LoadAsync, before the normal load, run a per-type shim that reads the legacy LD-{TypeName} JSON string from PlayerPrefs, JSON-deserializes it, re-saves through dataManager.Update + Save (which now routes to MemoryPack automatically), and deletes the legacy key:
private async UniTask MigrateLegacyJsonToMemoryPack(){ await this.allUserDataTypes.ForEachAsync(async type => { var legacyKey = $"LD-{type.Name}"; var json = PlayerPrefs.GetString(legacyKey); if (string.IsNullOrWhiteSpace(json)) return; try { var data = await this.jsonSerializer.DeserializeAsync(type, json); this.dataManager.Update(data); this.dataManager.Save(type); // [MemoryPackable] → written as MemoryPack PlayerPrefs.DeleteKey(legacyKey); // migrated — drop the legacy entry } catch (Exception e) { this.logger.Error($"Migrate '{type.Name}' failed; legacy key kept for retry: {e}"); } }); this.dataManager.FlushAll();}Per-type try/catch is mandatory — one corrupt/incompatible legacy entry must not block the others, and the legacy key is deliberately kept on failure so migration retries on the next boot.
Verification
Section titled “Verification”- On an install that has legacy JSON saves: launch once, confirm the log shows the per-type migration, the value is intact, and the legacy
LD-{TypeName}PlayerPrefs key is gone (binary key present instead). - On a fresh install: no legacy keys → shim is a no-op; normal MemoryPack load.
- A failing type keeps its legacy key and re-logs every boot — that is by design (retry), but a persistent failure means the JSON→model mapping is wrong; fix the model, don’t delete the key blindly.
Sequencing
Section titled “Sequencing”Ship the model-annotation change and the manager-migration change together (they can be separate commits, but must release together): until both land, CanSerialize returns false and the app silently keeps writing JSON. Annotate every IWritableData model and every nested DTO in the same pass — a half-annotated graph throws at (de)serialize time.