Skip to content

t1k:unity:base:userdata-memorypack

FieldValue
Modulebase
Version5.116.6
Effortlow
Tools—

Keywords: cross-assembly union, iwritabledata, localdataonly, memorypackable, memorypackconstructor, memorypackformatter, memorypackformatterbootstrap, memorypackignore, memorypackorder, memorypackunion, memorypackunionformatter, nogenerate, odinserialize, persistence, RegisterFormatter, save data, union formatter, user data, userdata, userdataloadedsignal, userdatamanager, versiontolerant

/t1k:unity:base:userdata-memorypack

UserData is runtime-persisted player save state (progress, settings, unlocked items). A UserData model is a plain C# class that implements IWritableData and is serialized to MemoryPack binary at runtime, then stored in PlayerPrefs. UserDataManager eager-loads every model once at boot; feature code reads via Get<T>() and persists via Save<T>().

Scope: this skill covers the MemoryPack save format ([MemoryPackable] + IWritableData). It is the save-data counterpart of the static-config t1k-unity-base-blueprint-csv skill (CSV blueprints are read-only design data; UserData is read-write player state). To port an existing JSON-serialized model, use t1k-unity-base-userdata-migrate.

The model class — TheOne.Data (com.theone.data) + MemoryPack

Section titled “The model class — TheOne.Data (com.theone.data) + MemoryPack”
namespace MyGame.Features.Foo.Models
{
using MemoryPack;
using Sirenix.Serialization; // [OdinSerialize] — editor tooling only
using TheOne.Data; // IWritableData
[MemoryPackable(GenerateType.VersionTolerant)]
public sealed partial class FooLocalData : IWritableData
{
[MemoryPackOrder(0)] [OdinSerialize] public bool IsUnlocked { get; set; }
[MemoryPackOrder(1)] [OdinSerialize] public string ActiveId { get; set; } = "";
[MemoryPackOrder(2)] [OdinSerialize] public Dictionary<string, int> Counters { get; set; } = new();
[MemoryPackIgnore] public bool HasProgress => this.Counters.Count > 0; // computed → not persisted
}
}
  • Base contract: IWritableData — an empty marker interface (TheOne.Data). It is the reflection anchor UserDataManager discovers (typeof(IWritableData).GetDerivedTypes()), so a new model needs no DI registration and no per-feature loader — it is picked up automatically. (There is no [UserData] attribute and no ILocalData/IUserData interface — IWritableData is the single base.)
  • [MemoryPackable(GenerateType.VersionTolerant)] — mandatory on every save model. VersionTolerant is the standard mode for save data: order-tagged members can be safely added/removed within limits without breaking existing saves. (Un-annotated IWritableData silently falls back to JSON — see Gotchas.)
  • partial — mandatory. MemoryPack’s source generator emits the other half of the class. Forgetting it is a compile error (the #1 mistake).
  • [MemoryPackOrder(n)] — on every persisted member, sequential from 0 in declared order. The number is the wire tag; never reuse a freed number for a different member.
  • [MemoryPackIgnore] — on computed / derived / get-only members. Required on get-only properties (MemoryPack has no way to deserialize into them → generator error without it).
  • [MemoryPackInclude] — required on every persisted member of an internal [MemoryPackable] class — including public members. Inside an internal LocalData class a member left without it is silently skipped — no compile error; the value is never written and reads back as its type default on the next load (silent data loss). This bites internal / private / protected members, non-public setters ({ get; private set; }), and genuinely public members of the internal class (observed: UITemplate#961 dropped a public PassedLevels until [MemoryPackInclude] was added). Because the LocalData convention is internal partial class … : IWritableData, mark every persisted member [MemoryPackInclude] next to its [MemoryPackOrder] — do not reason about per-member accessibility. See Gotchas.
  • [MemoryPackConstructor] — on a hand-written constructor for immutable/record-like DTOs (also stack [JsonConstructor] if the type is still read from cloud JSON).
  • [OdinSerialize] — keep it where present. It has nothing to do with the runtime wire format; it lets Odin-powered editor tooling (the UserDataToolModule inspector) introspect/edit the same members at edit time. Add it only where Odin needs it (private setters; Dictionary/HashSet/interface-typed members) — not universally mandatory, but never remove it where already present.
  • [LocalDataOnly] — mark a model to exclude it from cloud sync (device-local only, e.g. SoundSetting).
[MemoryPackable(GenerateType.VersionTolerant)]
public sealed partial record Player(
[property: MemoryPackOrder(0)] string Id,
[property: MemoryPackOrder(1)] string? Name);

Polymorphic / interface-typed members → [MemoryPackUnion]

Section titled “Polymorphic / interface-typed members → [MemoryPackUnion]”
[MemoryPackable]
[MemoryPackUnion(0, typeof(DefaultRewardEntry))]
[MemoryPackUnion(1, typeof(CardRewardEntry))]
public partial interface IRewardEntry
{
[MemoryPackIgnore] string ClaimViewType { get; } // interface members that are computed → ignore
}

Union tags must stay stable across releases — they are the wire discriminator. Reusing or reordering a tag silently corrupts existing saves on deserialize.

Cross-assembly unions → [MemoryPackUnionFormatter] + bootstrap

Section titled “Cross-assembly unions → [MemoryPackUnionFormatter] + bootstrap”

When the union interface and its concrete types live in different assemblies, [MemoryPackUnion] on the interface can’t be used (it would invert the dependency direction) — use an external [MemoryPackUnionFormatter(typeof(IInterface))] class with a frozen tag table instead. Registration is NOT automatic: the generated initializer is namespaced to the union interface, not the formatter class (<InterfaceNamespace>.<Formatter>Initializer.RegisterFormatter()), and must be called from a [RuntimeInitializeOnLoadMethod(AfterAssembliesLoaded)] bootstrap — plus [SetUp] in EditMode tests, since that lifecycle method never fires there. Full code walkthrough: references/advanced-formatters.md § “Cross-assembly unions”.

Serializer selection — automatic, per type

Section titled “Serializer selection — automatic, per type”

MemoryPackSerializer.CanSerialize(type) returns true iff the type carries [MemoryPackable]. DataManager matches each type to a (serializer, storage) pair at runtime: [MemoryPackable] → MemoryPack + PlayerPrefsBinaryDataStorage (byte[]); everything else → JsonSerializer + PlayerPrefsTextDataStorage (string). No per-model wiring — the attribute alone routes it. (Requires the X_MEMORYPACK scripting define; MemoryPack 1.21.4 in this stack.)

Storage key = type.GetKey() — the [TheOne.Extensions.Key("…")] value on the class, or the type name if no [Key].

Loading & runtime wiring — centralized via UserDataManager

Section titled “Loading & runtime wiring — centralized via UserDataManager”

UserDataManager (GameFoundation.Scripts.UserData, package com.gdk.core) is an IAsyncEarlyLoadable that eager-loads every IWritableData once at boot, then fires UserDataLoadedSignal (UserCloudDataLoadedSignal after cloud fetch/merge). It also implements IPauseListener (auto-saves all models on app pause) and IDisposable (auto-saves on teardown). Registered once in GameFoundationVContainer:

builder.Register<UserDataManager>(Lifetime.Singleton).AsSelf().AsImplementedInterfaces();
builder.RegisterDataManager(); // TheOne.Data serializers (Json + MemoryPack)
builder.RegisterPlayerPrefsDataStorages(); // binary (MemoryPack) + text (JSON) storages
builder.DeclareSignal<UserDataLoadedSignal>();

Adding a new UserData model is therefore one step: define the [MemoryPackable] partial class : IWritableData. No asset, no Addressable, no DI line, no loader.

Consuming a model (managed / VContainer code)

Section titled “Consuming a model (managed / VContainer code)”

Inject UserDataManager and always read through a computed property — never cache the Get<T>() result in a field. Mutate the returned instance, then explicitly Save<T>() — there is no dirty flag / auto-save-on-mutation. Two reasons the computed property is mandatory: (1) Get<T>() is cache-only and throws InvalidOperationException if called before LoadAsync completes, so a field initialized at construction throws; (2) it keeps every read on the manager’s live cached instance — a stale field copy risks mutating a detached object that Save<T>() will not persist. The idiomatic wrapper is a controller with a computed Data property:

public sealed class FooUserDataController
{
private readonly UserDataManager userDataManager;
[Preserve] public FooUserDataController(UserDataManager userDataManager) => this.userDataManager = userDataManager;
public FooLocalData Data => this.userDataManager.Get<FooLocalData>(); // ALWAYS a computed property — never cache in a field (cache-only, throws pre-boot; field copy detaches from Save)
public void Save() => this.userDataManager.Save<FooLocalData>(); // persist NOW (MemoryPack → PlayerPrefs)
public void Unlock() { this.Data.IsUnlocked = true; this.Save(); } // mutate → explicit Save
}

Get<T>() throws InvalidOperationException if called before LoadAsync completes. Code that runs early gates on UserDataLoadedSignal before its first Get<T>(). SaveAllAsync(force) persists every model at once (used by app-level save points).

Non-MemoryPack-native member types → custom formatter

Section titled “Non-MemoryPack-native member types → custom formatter”

A member whose type MemoryPack can’t serialize natively (e.g. R3 ReactiveProperty<T>) needs [MemoryPackAllowSerialize] on the member plus a registered MemoryPackFormatter<T>, registered in both runtime and editor contexts — RuntimeInitializeOnLoadMethod does not fire in edit mode / EditMode tests, and the editor UserData tool deserializes in edit mode. Code sample: references/advanced-formatters.md § “Non-MemoryPack-native member types”.

  • Naming — all models end in …Data. Use <Feature>LocalData (dominant), <Feature>UserData, or <Feature>PlayerData (account/identity-scoped). Prefer *LocalData.
  • Layout — Assets/.../Features/<Feature>/Scripts/Models/<Feature>LocalData.cs, paired with a Scripts/Controllers|Services/<Feature>UserDataController.cs.
  • asmdef — MemoryPack and Sirenix (Odin) are auto-referenced (source-generator / precompiled DLLs), so a model’s assembly usually needs no explicit reference for them; the IWritableData type comes from TheOne.Data.
  • Enter Play mode, exercise the feature, mutate + Save<T>(), then relaunch (or call SaveAllAsync + reload) and confirm the value round-trips.
  • Confirm the model actually uses MemoryPack, not the silent JSON fallback: the stored PlayerPrefs entry for type.GetKey() should be binary (via PlayerPrefsBinaryDataStorage), and the UserDataToolModule editor panel should list the model.
  • Schema change (add/remove/reorder a member): keep [MemoryPackOrder] numbers stable for surviving members; VersionTolerant tolerates additions/removals but not reusing an old order number for a new meaning.
  • Missing [MemoryPackable] = silent JSON fallback. A new IWritableData with no [MemoryPackable] still “works” — via JsonSerializer + text storage — so the bug is invisible until you expected binary/version-tolerant behavior. Always annotate.
  • partial is mandatory — class Foo → sealed partial class Foo. This is the most common compile error.
  • No dirty flag. Mutating the instance returned by Get<T>() does not persist it. Call Save<T>() explicitly (or rely on the app-pause / dispose / SaveAllAsync blanket saves). A missing Save<T>() after a mutation is a realistic data-loss bug.
  • Get<T>() throws before boot load completes — gate early callers on UserDataLoadedSignal.
  • Never cache the Get<T>() result in a field — always a computed Data property. Constructor-inject UserDataManager, then public FooLocalData Data => this.userDataManager.Get<FooLocalData>();. A field initialized at construction throws (pre-boot), and — worse — a stale field copy detaches from the manager’s cached instance, so mutations to it never reach Save<T>() → silent data loss. Re-reading through the property every access keeps you on the canonical instance.
  • [MemoryPackIgnore] on every computed/get-only member — omitting it on a get-only property is a generator error.
  • Members silently drop without [MemoryPackInclude] on an internal class. For an internal [MemoryPackable] LocalData class, every persisted member needs [MemoryPackInclude] or it is skipped with no compile error — the value is never written and reads back as its type default on the next load (silent data loss). This includes internal/private/protected members, public properties with a non-public setter ({ get; [Preserve] private set; }), and genuinely public members of the internal class (empirically observed in UITemplate#961 — a public HashSet<int> PassedLevels on an internal partial class was dropped until [MemoryPackInclude] was added). Rule of thumb: an internal LocalData class → mark every persisted member [MemoryPackInclude] next to [MemoryPackOrder]; don’t reason about per-member accessibility. [OdinSerialize] (editor tool) and [MemoryPackInclude] (runtime wire format) are independent — both are required on the same member.
  • Union tags are the wire format — never reuse/reorder [MemoryPackUnion]/[MemoryPackUnionFormatter] tags; a collision silently corrupts saves. Keep a frozen tag-table comment.
  • Cross-assembly union formatters don’t auto-register — the generated initializer is namespaced to the union interface (<InterfaceNamespace>.<Formatter>Initializer.RegisterFormatter()), not the formatter class, and must be called from a [RuntimeInitializeOnLoadMethod(AfterAssembliesLoaded)] bootstrap (plus [SetUp] in EditMode tests). Running the formatter’s static cctor does nothing.
  • Custom formatters need the editor registration too — [UnityEditor.InitializeOnLoadMethod] mirror, or the editor UserData tool throws in edit mode.
  • Keep [OdinSerialize] — it drives the Odin editor inspector, independent of the MemoryPack runtime format. Removing it breaks editor tooling for that member.
  • Editor ClearUserData wipes ALL PlayerPrefs (PlayerPrefs.DeleteAll()), not just UserData — a foot-gun in UserDataToolModule.
  • Submodule models are READ-ONLY from the consumer side. To change a model shipped in com.gdk.core / com.theone.data, PR the owning repo — not the consumer project.