Skip to content

EntitySerializer Class

Definition

Namespace: Brine2D.ECS.Serialization

Serializes and deserializes entities to/from JSON. Uses System.Text.Json with support for custom converters. Works automatically with ANY component type — no registration needed.

C#
public class EntitySerializer

Inheritance System.Object → EntitySerializer

Remarks

Behaviors are not serialized. Only components are persisted. Re-add behaviors after restore (e.g., by instantiating through a prefab) or add them manually.

Entity ID remapping. When a world is restored, every entity receives a new runtime ID assigned by the global counter. The original IDs captured in the snapshot are used only to reconstruct the parent–child hierarchy and are discarded afterwards. Any component that stores a cross-entity reference as a long entity ID will hold a stale value after restore. Re-resolve such references by entity name or tag after calling RestoreWorldFromSnapshot\(IEntityWorld, WorldSnapshot\).

NativeAOT / trimming. This class uses runtime reflection and dynamic JSON serialization to handle arbitrary component types. It is not compatible with NativeAOT or IL trimming. Use AotEntitySerializer with an explicit ComponentTypeRegistry when publishing with trimming or NativeAOT enabled.

Properties
Options Gets the current JSON serializer options \(for advanced customization\).
Methods
CreateDefaultOptions() Creates the default System.Text.Json.JsonSerializerOptions used by both EntitySerializer and ComponentTypeRegistry.
CreateSnapshot\(Entity\) Creates a snapshot of an entity.
CreateWorldSnapshot\(IEntityWorld\) Creates a snapshot of the entire world.
FindComponentType\(string\) Finds a component type by its full name or simple name. Searches all loaded assemblies.
LoadAndRestoreWorldAsync\(IEntityWorld, string, CancellationToken\) Loads and restores a world from a file. CLEARS the existing world first!
LoadWorldAsync\(string, CancellationToken\) Loads a world snapshot from a file.
RegisterConverter\(JsonConverter\) Registers a custom JSON converter for a specific type. Use this to provide custom serialization for user-defined types.
RegisterConverters\(JsonConverter\[\]\) Registers multiple custom JSON converters.
RestoreComponent\(Entity, string, JsonElement\) Restores a component from JSON data onto an entity. The component is fully deserialized before being attached so that OnAdded() fires with all restored values in place.
RestoreEntity\(IEntityWorld, EntitySnapshot\) Restores a single entity from a snapshot.
RestoreWorldFromSnapshot\(IEntityWorld, WorldSnapshot\) Restores entities from a snapshot into the world, preserving the parent–child hierarchy. CLEARS the existing world's entities first, but leaves registered systems intact.
SaveWorldAsync\(IEntityWorld, string, CancellationToken\) Saves a world snapshot to a file.