Save and load
Write a whole C# ECS world to bytes with World.Save and read it back with World.Load in any process: same ids, raw unmanaged rows, Nino for managed data.
A server restarts and must come back with its world: players where they stood, timers where they were, links between
entities intact. world.Save(output) writes the entities (ids and versions), their components and the singletons as
bytes, and world.Load(bytes) puts them into a world of this process or another one. Unmanaged components are their
raw rows, one block per column; managed ones, and the components marked [NinoType], go through
Nino. Saving and
loading again into the same buffers allocates nothing.
When to use it
Use it for
Persistence across restarts, replays on disk, crash dumps, shipping a world to another process (a test harness, a replay viewer), keeping data through a hot reload.
Skip it for
Rolling back inside one process: a snapshot is faster and needs no encoding. Moving a
player to another server: SaveEntities writes just the group.
Saving only what persists of an entity and loading it onto a live one: a record
is SaveEntities with a ComponentSet, loaded by LoadEntitiesInto.
How to use it
Declare the components
Unmanaged components need nothing. A managed component (one with a string, an array, a class) needs a Nino formatter:
mark it [NinoType] and make it partial. The EasyEcs package brings Nino with its generator, so the project
references nothing else. Mark an unmanaged component [NinoType] too when its shape will change between builds
(below).
<PackageReference Include="EasyEcs" Version="4.*" />using Nino.Core;
public record struct Stock(int Gold, int Wood) : IComponent; // unmanaged: saved as raw rows
public record struct Clock(long Tick) : ISingletonComponent;
[NinoType]
public partial record struct PlayerName(string Value) : IComponent; // managed: Nino writes itSave
Save writes into any IBufferWriter<byte>. A NinoArrayBufferWriter is written directly; another writer gets a
copy from the world's own buffer.
world.CreateEntity(new PlayerName("alice"), new Stock(10, 3));
world.SetClock(1234);
var output = new NinoArrayBufferWriter();
world.Save(output); // entities, components, singletons
File.WriteAllBytes("world.sav", output.WrittenSpan.ToArray());Load
Load replaces the world's entities, components and singletons with the save's. Entities keep their ids and
versions, so EntityIds stored in components still point at the same entities, and handles made before the save work
again.
using var restarted = new World();
restarted.Load(File.ReadAllBytes("world.sav")); // same ids, values and clock
long tick = restarted.Clock.Tick; // 1234What a save holds
| Saved | Not saved |
|---|---|
| Every alive entity, with its id and version | Systems, WorldOptions |
| Every component, unmanaged as raw rows, managed through Nino | Indexes (they rebuild on the next lookup) |
| Disabled components, with their kept values | Groupings (Load follows this world's GroupBy calls) |
DynamicBuffer<T> elements | Change ticks (every loaded row counts as written, or none with markWritten: false: restart) |
| Every singleton |
Types are recorded by their Nino type id (a hash of the namespace-qualified name), and each column is a length-prefixed slice, so a load skips the components this process has no type for. A type is found when the process used it, or when the generator registered it: every component and singleton of a compilation that uses EasyEcs is registered when its module loads.
Restart without counting the load as changes
A restart resumes the world of the previous process: it saves between two ticks, the new process loads the save,
adds its systems and goes on. By default every loaded row counts as written, so a [Changed<T>] system that writes
records or replicates would send the whole world again on its first run. Load(bytes, markWritten: false) loads the
rows without a change tick: no row counts as written or removed, also for the systems added after the load, and
what code writes from then on is seen as usual.
public record struct Balance(int Gold) : IComponent, ITrackChanges; // tracked: written records are saved
public record struct Outbox(int Records) : ISingletonComponent;
public class SaveBalances : EcsSystem
{
[ForEach, Changed<Balance>]
private static void Save(ref Outbox outbox) => outbox.Records++; // one record per changed balance
}var bank = new World(); // the old process
bank.SetOutbox(0);
bank.CreateEntity(new Balance(100));
var previous = new NinoArrayBufferWriter();
bank.Save(previous); // between two ticks
using var resumed = new World(); // the new process
resumed.Load(previous.WrittenSpan, markWritten: false); // the records hold these values
resumed.AddSystem<SaveBalances>();
resumed.Update();
int records = resumed.Outbox.Records; // 0: no loaded balance is a changeThe singletons come from the save (Outbox here), so the new process adds only those the save did not hold, as at
startup.
A system added later to a world that already holds its state, whatever wrote it, can start from the current tick
instead: world.AddSystem<T>(changesFromNow: true) makes its first run visit only what is written after the call
(ticks).
When the code changed
How a component may change depends on how it is written. A plain unmanaged component is its raw rows: the save records
its size and a hash of its fields (names, types, layout attributes), and only the same shape loads them. A
[NinoType] component, managed or unmanaged, is written by its Nino formatter, and its
format decides what may change: Positional (the default) reads
only the shape it wrote, VersionTolerant reads rows written before members were appended, Keyed also takes
members inserted, removed or reordered. A load refuses what it cannot read, with an InvalidDataException, and leaves
the world as it was:
| Change since the save | Load |
|---|---|
| A component type added | Loads: the new type has no rows |
| A component type removed | Loads: its slices are skipped (its data is dropped) |
| A component type renamed or moved to another namespace | Loads with [NinoFormerName("Old.Namespace.Name")] on it; skipped without |
| Fields of a raw unmanaged component changed (added, removed, retyped, renamed) | InvalidDataException |
Members appended to a VersionTolerant or Keyed component | Loads: the new members keep their defaults |
| A change the component's Nino format does not allow (its slice no longer reads to the last byte) | InvalidDataException |
A component switched between raw rows and [NinoType] | InvalidDataException |
| Two types of the process with one id (one name, or a former name that is another's) | InvalidDataException: rename one |
| Bytes that are not a save, or a damaged one | InvalidDataException |
So a component whose shape will change is a [NinoType] from its first save. It stays unmanaged (a column of
values, no references), and Nino writes it value by value instead of as one block:
[NinoType(format: NinoFormat.VersionTolerant)]
public partial record struct Rank(int Tier, int Points) : IComponent; // the first build
// A later build renames it and appends a member: old saves load, Season is 0 in their rows.
[NinoType(format: NinoFormat.VersionTolerant), NinoFormerName("Rank")]
public partial record struct Standing(int Tier, int Points, int Season) : IComponent;A raw component cannot change shape. Add a new component type instead: a build that has both loads the old save, a system converts the old component into the new one, and a later build drops the old type.
public record struct Crafting(int Recipe, int Progress) : IComponent; // saved as raw rows
public record struct Workshop(int Recipe, int Progress, int Queue) : IComponent; // the new shape
// Runs in the build that knows both types: every loaded Crafting becomes a Workshop.
// A later build deletes Crafting and this system.
public class UpgradeCrafting : EcsSystem
{
[ForEach]
static void Upgrade(Entity player, in Crafting old)
{
player.SetWorkshop(old.Recipe, old.Progress, Queue: 0);
player.RemoveCrafting();
}
}try
{
restarted.Load(output.WrittenSpan);
}
catch (InvalidDataException)
{
// a component changed since this save: the world is as it was before the call
}Components in plugins
The id lookup is process-wide. While a plugin's old version and its new one are both loaded, their types share ids and
a load refuses them as ambiguous. Unload the old version first (the hot reload
order: save, RemoveTypes, unload, load the new version, Load), or keep the components you save in an assembly
that is never reloaded, such as a contracts assembly shared by the host and the plugins.
Full example
Two players, one following the other, and a clock: the world is saved into a buffer and loaded into a new world, as a
restarted process would do. Put the files in a console project that references EasyEcs
(declare the components) and run it with dotnet run.
It prints:
clock: 1234
0v1 alice at (3, 4)
1v1 bob at (5, 6)
bob follows aliceThe new world has the same ids, the managed names came back through Nino, the singleton clock kept its tick, and
Bob's Follows still names Alice without any rewriting.
How to use it fast
| Instead of | Do | Why |
|---|---|---|
| A new buffer per save | One NinoArrayBufferWriter, ResetWrittenCount() before each save | Save allocates nothing once its buffers are large enough |
Another IBufferWriter<byte> | NinoArrayBufferWriter | Written directly, without the copy from the world's buffer |
| A new world per load | Load into the same world | Its rows are reused: nothing allocated once warm |
| Managed components where values would do | Unmanaged components (ids, numbers, fixed arrays) | Raw rows are one block per column; Nino encodes value by value |
[NinoType] on unmanaged components that never change | Raw rows for those, [NinoType] where the shape will change | A raw column is one copy |
Your own serializer over a Query | Save / Load | Ids, versions, buffers, disabled values and singletons come along |
100,000 entities in two tables, saved into a reused buffer and loaded back (SnapshotBenchmark):
| Case | Mean | vs baseline | Allocated |
|---|---|---|---|
| Save | 262 μs | — | 0 B |
| Load | 1.00 ms | — | 0 B |
What it costs
- Size: for unmanaged components, the rows themselves (padding bytes cleared, so equal worlds save equal bytes),
plus presence bits, ids and versions; managed and
[NinoType]components as Nino writes them; each type's id once. - Time: O(entities × components) both ways.
- Allocation: none on a repeated
Saveinto aNinoArrayBufferWriter, none on a repeatedLoadinto the same world; managed values a load reads are new objects. - Not while a pass iterates: both take the structural gate.
Pitfalls
| Mistake | What happens | Caught by |
|---|---|---|
A managed component without [NinoType] | Save throws InvalidOperationException (no formatter) | At run time |
A Nino.Generator reference older than the Nino of EasyEcs | A package downgrade: remove the reference, the EasyEcs package brings the generator | Restore (NU1605) |
An Entity handle in a component | A managed column Nino cannot write | EECS017 |
| Editing the fields of a saved raw component | Old saves are refused | [NinoType(format: NinoFormat.VersionTolerant)] from the first save, or a new component type |
| Renaming a component or moving its namespace | Old saves load without it | [NinoFormerName] with the old full name |
| Old and new plugin versions loaded at once | Ambiguous names: InvalidDataException | Unload the old version first |
| Saving or loading from another thread | Races with the owner thread | EECS014 |
Compared with other libraries
Friflo writes JSON (EntitySerializer), DefaultEcs has a binary serializer that creates a new world each time, and
Arch saves through a separate package. 10,000 units with a position and a stock, saved and loaded back:
Save and load 10,000 units
- EasyEcs
- Other libraries
BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.
Data table
| Library | Case | Mean | vs EasyEcs | Allocated |
|---|---|---|---|---|
| EasyEcs | SaveLoad | 146 μs | 1.00× | 0 B |
| Friflo.Engine.ECS | Json | 20.8 ms | 143× | 6.52 MB |
| DefaultEcs | Binary | 4.33 ms | 30× | 4.37 MB |
Related
Last updated on
How is this guide?
Snapshots
Copy a whole world into memory with Capture and put it back with Restore, for rollback netcode, replays and test resets, allocation-free when reused.
Migration and unload
Move a player and what it owns to another world or server with SaveEntities and MoveEntities, and hot-reload game logic with a collectible AssemblyLoadContext.