EasyEcs

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 ComponentSet and LoadEntitiesInto (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 rewritten

Descendants 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 kept
var 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 ArgumentException before 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), pass markWritten: 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 and Since filter 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.
  • SaveEntities with 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.
  • EntityId fields are rewritten as below, onto the entities given; a ChildOf whose parent is not in the record is not set.
  • LoadEntitiesInto is a structural change: owner thread only (EECS014), not while a pass iterates (InvalidOperationException), never in a parallel method (EECS010), and in a [ForEach] method only when it takes Entity or World (EECS013).
  • 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 namedBecomes
An entity of the groupThe id of its new entity
Any other entity (it stayed behind)EntityId.Null
The parent of a ChildOf that stayed behindThe 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 gold

Every 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 ofDoWhy
SaveEntities + LoadEntities between worlds of one processMoveEntitiesRows copied, no encoding
A new buffer per migrationOne NinoArrayBufferWriter, ResetWrittenCount() each timeNo allocation once it is large enough
Many small migrations of one entityOne migration of the whole groupA save's fixed cost (the types by id) is paid once
SaveEntities of whole entities when only some components persistA ComponentSetThe runtime components are not written, and need no formatter
A ComponentSet built for every saveOne static readonly setEach With copies the set
A reload that rebuilds the worldRemoveTypes, then LoadThe 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):

CaseMeanvs baselineAllocated
SaveAndLoad222 μs1.00×0 B
Move165 μs0.74×0 B
SaveAndLoadOne2.22 μs0.01×0 B
SaveRecord104 ns0.00×0 B
LoadRecord722 ns0.00×0 B
BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.
CasePlayersMeanvs baselineAllocated
RemoveTypes10000247 μs—2.95 KB
RemoveTypes1000002.38 ms—2.95 KB
BenchmarkDotNet 0.15.2, .NET 10.0.13, Intel Xeon Processor 2.10GHz, 4 cores, Ubuntu 24.04.5 LTS.

What it costs

  • Migration: O(entities × components); the rewrite of ids is a lookup per EntityId field.
  • Allocation: none for SaveEntities, LoadEntities, LoadEntitiesInto and MoveEntities once 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

MistakeWhat happensCaught by
Moving a parent without its childrenThe children are destroyed with the originalCollect the group with Descendants
Collecting the group with Children onlyGrandchildren are left out, and destroyed with their parentDescendants walks every level
EntityIds in a List<T> inside a componentNot rewritten: they name entities of the old worldUse fields, a buffer or a relation
An Entity handle in a componentNot saved, not rewrittenEECS017
Loading the new plugin before unloading the old oneAmbiguous type ids: InvalidDataExceptionThe reload order above
Keeping references to the old plugin's systemsThe context is never collectedDrop them after RemoveTypes
RemoveTypes during an update or a passInvalidOperationExceptionAt run time
Restoring a snapshot taken before RemoveTypesInvalidOperationExceptionAt run time
Migrating from another threadBoth worlds belong to their owner threadEECS014
A component that persists left out of the record's setNot saved: the loaded entity keeps its own value, or has noneBuild the set from the persisting components, in one place
A record loaded with LoadEntitiesNew entities beside the live onesLoadEntitiesInto with the live entities
LoadEntitiesInto with another number of entities than the save holds, or a stale oneArgumentException; nothing changesOne live entity per saved entity, in save order
A restored record seen as changedA Changed<T> saver or replicator sends it straight backmarkWritten: false
Replicating only [Changed<T>] rows after a markWritten: false loadA client that has not seen the entity never gets the restored valuesSend the full state to a new client
Edit on GitHub

Last updated on

How is this guide?

On this page