Skip to content

Game.BeginPrefabSerializationSystem

Assembly: Assembly-CSharp
Namespace: Game.Serialization

Type: class

Base: GameSystemBase

Summary:
BeginPrefabSerializationSystem prepares prefab entities for save/serialization. It collects entities that represent loaded prefabs, maps their PrefabData indices to the actual Entity instances, coordinates checks for prefab references (so any external references are marked dirty when required), and computes compacted/normalized PrefabData indices into LoadedIndex buffers so the serializer can write a contiguous list of prefabs. The system schedules several Burst-compiled chunk jobs for these tasks and integrates with the SaveGame, CheckPrefabReferences and update subsystems.


Fields

  • private SaveGameSystem m_SaveGameSystem
    Reference to the SaveGameSystem used to detect saving context (Purpose.SaveGame) and to coordinate saved-prefab checks.

  • private CheckPrefabReferencesSystem m_CheckPrefabReferencesSystem
    Reference to the system that tracks and validates prefab references; used to mark prefab references dirty and to begin/end prefab checks.

  • private UpdateSystem m_UpdateSystem
    Reference to a general update system used here to advance the PrefabReferences update phase.

  • private EntityQuery m_EnabledPrefabsQuery
    EntityQuery targeting entities with PrefabData (used to iterate/collect enabled prefabs into an ArchetypeChunk list).

  • private EntityQuery m_LoadedPrefabsQuery
    EntityQuery targeting entities with LoadedIndex (used to determine number of loaded prefabs and to build a mapping array of index -> Entity).

  • private TypeHandle __TypeHandle
    Container struct holding all Entity/Component/Buffer type handles used by the system and its jobs. Populated during OnCreateForCompiler.

Properties

  • None (no public properties are declared on this type)

Constructors

  • public BeginPrefabSerializationSystem()
    Default constructor (tagged with [Preserve]). The system is initialized through OnCreate and OnCreateForCompiler rather than constructor logic.

Methods

  • protected override void OnCreate()
    Initializes references to other systems and compiles the queries used by this system:
  • Gets SaveGameSystem, CheckPrefabReferencesSystem and UpdateSystem from the World.
  • Creates the entity queries m_EnabledPrefabsQuery (PrefabData) and m_LoadedPrefabsQuery (LoadedIndex).
  • Type handles are assigned in OnCreateForCompiler.

  • protected override void OnUpdate()
    Main runtime logic executed each frame/update:

  • Calculates the number of loaded prefabs and allocates a NativeArray sized to that count.
  • Schedules BeginPrefabSerializationJob (IJobChunk) which:
    • Reads PrefabData and Entity arrays from chunks,
    • Disables the PrefabData enabled mask for processed prefabs,
    • Writes Entities into the m_PrefabArray at positions determined by PrefabData.m_Index (supports negative indices by mapping to the end).
  • Calls m_CheckPrefabReferencesSystem.BeginPrefabCheck(...) with the prefab Entity array to perform reference collection; updates the PrefabReferences phase via m_UpdateSystem.Update(SystemUpdatePhase.PrefabReferences).
  • If saving (SaveGameSystem.context.purpose == Purpose.SaveGame), schedules CheckSavedPrefabsJob (IJobChunk) to mark prefabs as dirty when certain components/buffers exist or when Lock state differs; then registers the job as a user of PrefabReferences and updates that system.
  • Ends the prefab check (m_CheckPrefabReferencesSystem.EndPrefabCheck) and disposes the prefab Entity array after the dependent job completes.
  • Builds an ArchetypeChunk list of enabled prefabs (m_EnabledPrefabsQuery.ToArchetypeChunkListAsync) and schedules SetPrefabDataIndexJob (IJob) to:
    • Count enabled prefabs,
    • Gather and sort their PrefabData.m_Index values,
    • Compute compacted indices and write them into each entity's LoadedIndex dynamic buffer.
  • Disposes of the chunk list and sets base.Dependency to the scheduled job so the ECS runtime tracks the job dependencies.

  • protected override void OnCreateForCompiler()
    Helper called by generated/compiled code paths: assigns queries and calls __TypeHandle.__AssignHandles to populate component type handles used by jobs.

  • private void __AssignQueries(ref SystemState state)
    Internal helper (aggressively inlined) used during compiler-time initialization. The body in this class is effectively a no-op placeholder that creates and disposes an EntityQueryBuilder; real handle assignments are performed by __TypeHandle.__AssignHandles.

Additional internal types and jobs (described here for reference): - BeginPrefabSerializationJob (BurstCompile, IJobChunk)
- Inputs: EntityTypeHandle, ComponentTypeHandle
- Output: NativeArray m_PrefabArray
- For each chunk it reads Entity and PrefabData arrays, clears the enabled mask for PrefabData entries and stores the entity into m_PrefabArray at index computed from PrefabData.m_Index (handles negative indices by selecting a position from the end).

  • CheckSavedPrefabsJob (BurstCompile, IJobChunk)
  • Read-only component type handles for Locked, SignatureBuildingData, PlacedSignatureBuildingData, CollectedCityServiceBudgetData and buffer types for collected service fees/upkeep.
  • Uses PrefabReferences to SetDirty for entities that need to be re-serialized (e.g., locked or with changed component composition). Examines enabled/disabled state and component presence to determine if a prefab reference is dirty.

  • SetPrefabDataIndexJob (BurstCompile, IJob)

  • Input: NativeList of chunks with PrefabData enabled entries.
  • Operation:
    • Counts enabled prefabs and allocates a temporary NativeArray to collect all PrefabData.m_Index values.
    • For every enabled PrefabData, writes the original m_Index into the temp array and writes a LoadedIndex buffer with the original index.
    • Sorts the array of original indices and computes a compacted mapping (adjusting for negative indices by tracking num2) and writes the compacted index back into each PrefabData.m_Index.
  • Purpose: produce a contiguous set of indices used by the serializer and ensure each prefab entity contains a LoadedIndex buffer entry for the output order.

Usage Example

// Typical usage inside another system or mod: obtain the system instance and let the ECS scheduler run it.
// You normally don't call OnUpdate() manually; the system runs as part of the game's SystemGroups.
[Preserve]
protected override void OnCreate()
{
    base.OnCreate();
    var beginPrefabSystem = World.GetOrCreateSystemManaged<Game.Serialization.BeginPrefabSerializationSystem>();
    // beginPrefabSystem is now part of the world and will run automatically.
}

Notes and tips for modders: - This system is tightly coupled to the game's save/serialization flow. Modifying PrefabData.m_Index or LoadedIndex buffers can affect save ordering — be cautious and prefer using higher-level APIs if available. - Prefab reference checks rely on CheckPrefabReferencesSystem. If you add new component types that affect whether a prefab should be considered "dirty" for serialization, ensure CheckPrefabReferencesSystem is updated accordingly (or mark prefab references dirty via its API). - Jobs are Burst-compiled and use Unity.Collections/Entities APIs (IJobChunk/IJob). Ensure any custom data accessed in similar jobs is compatible with Burst and uses proper type handles and Native/Buffer access patterns.