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.
A player walks through a portal into another zone's world, or is handed to another server. Their entity, their items
and their pets must arrive together, still pointing at each other. SaveEntities / LoadEntities carry such a group
through bytes, MoveEntities copies it straight into another world of the thread, and both rewrite the EntityIds
inside the group to the new entities. A long-running server also replaces its game logic without a restart:
RemoveTypes takes a plugin's systems and components out of a world, so its collectible AssemblyLoadContext can
unload and a new version can load the saved data.
When to use it
Use it for
- Zone or map changes between worlds of one thread:
MoveEntities. - Handing a player to another server, or storing an offline player:
SaveEntities/LoadEntities. - A record of part of an entity, such as an actor's balance without its connection, loaded onto the entity it
already has: a
ComponentSetandLoadEntitiesInto(records). - Hot reload of game logic in a server that must not restart:
RemoveTypes.
Skip it for
Moving a whole world: Save / Load keeps every id. Entities that change "zone" inside one
world: a group or a component value is enough. Reloading types that are not in a collectible
context: the default context never unloads. A record of every component of an entity that does not exist yet:
SaveEntities without a set and LoadEntities create it.
How to use it
A group through bytes
SaveEntities(output, ids) writes the listed entities and their components (stale ids and repeats are skipped; no
singletons). LoadEntities(bytes, handles) creates them in another world, in this or another process, with new ids,
and writes their handles in save order.
using Nino.Core;
public record struct Sword(int Damage) : IComponent;
// Indexed by its owner: a hero's pets are found without a scan of every pet.
public record struct Pet(EntityId Owner) : IComponent, IIndexed<EntityId>
{
EntityId IIndexed<EntityId>.Key => Owner;
}var hero = world.CreateEntity(new Health(100));
world.CreateEntity(new Sword(10), new ChildOf(hero));
world.CreateEntity(new Pet(hero), new Health(20));
// Collect the group: the hero, what hangs on it, what points at it.
var group = new List<EntityId> { hero.Id };
foreach (var part in world.Descendants(hero)) group.Add(part.Id); // children, grandchildren and so on
foreach (var pet in world.PetIndex.Find(hero.Id)) group.Add(pet.Id); // the index, not a scan of every Pet
var bytes = new NinoArrayBufferWriter();
world.SaveEntities(bytes, group.ToArray()); // the group only
using var otherServer = new World();
var arrived = new Entity[group.Count];
int created = otherServer.LoadEntities(bytes.WrittenSpan, arrived); // new ids, links rewrittenDescendants walks depth first and lists each entity before its children, so the group holds every parent ahead of
what hangs on it: the order MoveEntities wants, since it destroys the originals last first and a child then goes
before its parent. Children lists one level only. A ChildOf cycle makes the walk throw
InvalidOperationException. Find what points at the hero (pets, followers) through an index on the field, as above,
or through a relation: a query that tests every Pet grows with the world, not with the
group.
A group to another world of the thread
MoveEntities(target, ids, moved) does the same between two worlds of the thread, without encoding: rows are copied,
ids rewritten, then the originals are destroyed. moved receives the new handles in order (default for a skipped
id).
using var nextZone = new World();
var moved = new Entity[group.Count];
int count = world.MoveEntities(nextZone, group.ToArray(), moved); // hero, sword and pet leave this world- The originals are destroyed with their children, so move a hierarchy together.
- Cleanup components stay on the destroyed originals, for their systems to release.
- Both worlds must be owned by the calling thread; moving a world into itself is refused (
ArgumentException).
A record of what persists
An actor's entity holds runtime state next to what persists: a connection, timers, a cache, and a bank balance that
must survive a restart. A ComponentSet names the components of the record, SaveEntities(output, ids, set) writes
those only (the others need no Nino formatter), and LoadEntitiesInto(bytes, entities) puts them onto entities that
exist already, such as the one the actor got when it was activated, before its record came back from the database.
Use a record when only part of an entity outlives the process (the rest is rebuilt by the code that activates it), or
when the entity is created before its data arrives. Build the set once, in a static readonly field, from the
components that persist; save into a reused NinoArrayBufferWriter and store the written bytes wherever the data
lives (a database row, a file, a message to another server).
public record struct Bank(long Gold) : IComponent;
public record struct Connection(int Socket) : IComponent; // runtime only: never saved
public static class Records
{
public static readonly ComponentSet Persistent = ComponentSet.Create().With<Bank>(); // built once
}var actor = world.CreateEntity(new Bank(500), new Connection(7));
var record = new NinoArrayBufferWriter();
world.SaveEntities(record, [actor.Id], Records.Persistent); // Bank only
// Later, maybe in another process: the actor is activated, then its record arrives.
var activated = world.CreateEntity(new Connection(9));
world.LoadEntitiesInto(record.WrittenSpan, [activated]); // Bank added, Connection keptvar restored = world.CreateEntity(new Connection(10));
// Instead of the call above: the record restored without counting as a change.
world.LoadEntitiesInto(record.WrittenSpan, [restored], markWritten: false);- The i-th saved entity loads onto the i-th entity given; the counts must match and every entity must be alive in
this world, or the call throws
ArgumentExceptionbefore changing anything. - Each entity moves table at most once, whatever the number of components it receives. Components the record holds are added or replace the entity's values; the others stay.
- Indexes, groups and change tracking follow as with
Set. A disabled component arrives disabled with its value. - A load is a write:
[Changed<T>]methods see the loaded components. When the record only restores what was there (an actor coming back from its database), passmarkWritten: false: every component the record holds ends with no change tick, also one that replaces a default (from a prefab, say), so a system that saves or replicates changed components does not send the record straight back. Components the record does not hold keep their ticks. - The price of
markWritten: false: the restored components are invisible to every[Changed<T>]method andSincefilter until code writes them. A replicator that sends changes to clients must send the full state itself to a client that has not seen the entity yet. - So one prefab per kind of actor serves both cases: a new actor keeps the prefab's defaults as its first state (written, so the next save stores them), and a restored one gets its record over them (not written). The Actors sample does this.
SaveEntitieswith a set also writes an entity that holds none of the set's components, as an empty entry, so the i-th saved entity still matches the i-th entity given.EntityIdfields are rewritten as below, onto the entities given; aChildOfwhose parent is not in the record is not set.- A framework that learns its types at run time builds the set by
Type:
public static class RuntimeRecords
{
public static readonly ComponentSet Persistent = ComponentSet.Create().With(typeof(Bank));
}How ids are rewritten
The generator records where every EntityId field of a component or buffer element is, private fields and nested
structs included. When a group arrives:
An EntityId field that named | Becomes |
|---|---|
| An entity of the group | The id of its new entity |
| Any other entity (it stayed behind) | EntityId.Null |
The parent of a ChildOf that stayed behind | The ChildOf is removed: the entity is a root here |
Ids inside collections (a List<EntityId> in a component) are not rewritten. Indexes and groups learn the arrivals,
and their tracked components count as written.
Unloading a plugin's types
world.RemoveTypes(assembly) (or RemoveTypes(context) for every assembly of an AssemblyLoadContext) removes
everything of the plugin from the world: its systems (their OnDestroy runs), singletons, indexes and groupings, and
its components from every entity. The entities stay, without those components. Tables that had such a column are
dropped with every cache naming them, so the world holds no reference to the assembly. Once every world removed it,
the collectible context can unload; when it does, EasyEcs forgets the types' save ids and reuses their component
bits once no live world mentions them.
Hot reload
Saves record types by id, so a reload keeps the plugin's data: save, remove the types, unload, load the new version, load the save.
using System.Buffers;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Loader;
public sealed class PluginContext() : AssemblyLoadContext("plugin", isCollectible: true);
public static class Plugins
{
public static Assembly Reload(World world, PluginContext old, PluginContext next, string path)
{
var saved = new ArrayBufferWriter<byte>();
world.Save(saved); // the plugin's components too, by type id
world.RemoveTypes(old); // its systems, singletons and components leave
old.Unload(); // collected once nothing else roots it
var plugin = next.LoadFromAssemblyPath(path);
RuntimeHelpers.RunModuleConstructor(plugin.ManifestModule.ModuleHandle); // registers its types for Load
world.Load(saved.WrittenSpan); // the new version's components take the values
return plugin; // then add its systems to the world
}
}The order matters: while both versions are loaded their types share ids, and a load would refuse them as ambiguous.
Keep the components the host owns (positions, ids) in an assembly that is never reloaded, and hold no references of
your own to the old version's types (systems, plugin objects), or the context cannot be collected. A
snapshot taken before RemoveTypes cannot be restored after it.
The HotReload sample runs the whole cycle and checks that the old context was collected and that the plugin's data carried over.
Full example
A hero with a sword (and a gem in the sword) and a pet walks into another zone: the group is collected with
Descendants and the pet index, moved with MoveEntities, and the pet still points at its hero. Then an actor's bank
comes back from an earlier run as a record, loaded with markWritten: false, and a [Changed<Bank>] saver finds
nothing to save until a deposit. Put the files in a console project that references EasyEcs
(dotnet add package EasyEcs) and run it with dotnet run.
It prints:
0v1 -> 2v1
1v1 -> 3v1
2v1 -> 4v1
3v1 -> 5v1
pet owner: 2v1, hero: 2v1
left behind: 0 entities
update after the load (500 gold):
update after a deposit:
saving 0v1: 650 goldEvery entity of the group gets a new id in the next zone (two ids were taken there), the pet's Owner names the
hero's new id, and nothing stays behind. The restored bank is not saved again on the update after the load; the
deposit is.
How to use it fast
| Instead of | Do | Why |
|---|---|---|
SaveEntities + LoadEntities between worlds of one process | MoveEntities | Rows copied, no encoding |
| A new buffer per migration | One NinoArrayBufferWriter, ResetWrittenCount() each time | No allocation once it is large enough |
| Many small migrations of one entity | One migration of the whole group | A save's fixed cost (the types by id) is paid once |
SaveEntities of whole entities when only some components persist | A ComponentSet | The runtime components are not written, and need no formatter |
A ComponentSet built for every save | One static readonly set | Each With copies the set |
| A reload that rebuilds the world | RemoveTypes, then Load | The host's entities and components stay where they are |
10 players with 99 items each, moved to another world and back through bytes and in memory, and one entity of four
components through bytes, and a record of two of its components saved and loaded onto an entity that holds the
others (MigrationBenchmark); a plugin with a tracked and an indexed component on every player, a
singleton, a system and an index, removed with RemoveTypes (UnloadBenchmark):
| Case | Mean | vs baseline | Allocated |
|---|---|---|---|
| SaveAndLoad | 222 μs | 1.00× | 0 B |
| Move | 165 μs | 0.74× | 0 B |
| SaveAndLoadOne | 2.22 μs | 0.01× | 0 B |
| SaveRecord | 104 ns | 0.00× | 0 B |
| LoadRecord | 722 ns | 0.00× | 0 B |
| Case | Players | Mean | vs baseline | Allocated |
|---|---|---|---|---|
| RemoveTypes | 10000 | 247 μs | — | 2.95 KB |
| RemoveTypes | 100000 | 2.38 ms | — | 2.95 KB |
What it costs
- Migration: O(entities × components); the rewrite of ids is a lookup per
EntityIdfield. - Allocation: none for
SaveEntities,LoadEntities,LoadEntitiesIntoandMoveEntitiesonce their buffers are large enough. RemoveTypes: O(entities with such components + tables + cached queries); it allocates, and it is cold: run it between updates, not in a tick.- Steady state: nothing. The unload support costs no time in worlds that never call
RemoveTypes.
Pitfalls
| Mistake | What happens | Caught by |
|---|---|---|
| Moving a parent without its children | The children are destroyed with the original | Collect the group with Descendants |
Collecting the group with Children only | Grandchildren are left out, and destroyed with their parent | Descendants walks every level |
EntityIds in a List<T> inside a component | Not rewritten: they name entities of the old world | Use fields, a buffer or a relation |
An Entity handle in a component | Not saved, not rewritten | EECS017 |
| Loading the new plugin before unloading the old one | Ambiguous type ids: InvalidDataException | The reload order above |
| Keeping references to the old plugin's systems | The context is never collected | Drop them after RemoveTypes |
RemoveTypes during an update or a pass | InvalidOperationException | At run time |
Restoring a snapshot taken before RemoveTypes | InvalidOperationException | At run time |
| Migrating from another thread | Both worlds belong to their owner thread | EECS014 |
| A component that persists left out of the record's set | Not saved: the loaded entity keeps its own value, or has none | Build the set from the persisting components, in one place |
A record loaded with LoadEntities | New entities beside the live ones | LoadEntitiesInto with the live entities |
LoadEntitiesInto with another number of entities than the save holds, or a stale one | ArgumentException; nothing changes | One live entity per saved entity, in save order |
| A restored record seen as changed | A Changed<T> saver or replicator sends it straight back | markWritten: false |
Replicating only [Changed<T>] rows after a markWritten: false load | A client that has not seen the entity never gets the restored values | Send the full state to a new client |
Related
Last updated on
How is this guide?
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.
Threading and parallel systems
How EasyEcs uses every core without locks on hot paths: one owner thread per world, parallel stages of non-conflicting systems and parallel [ForEach].