Skip to content

Game.Citizens.HouseholdInitializeSystem

Assembly: Assembly-CSharp
Namespace: Game.Citizens

Type: public class

Base: GameSystemBase

Summary:
Initializes newly created household entities at the end of a frame. This system runs a Burst-compiled IJobChunk (InitializeHouseholdJob) over entities that have a PrefabRef, Household, HouseholdCitizen buffer, CurrentBuilding and Resources buffer (and which are not marked Temp). For each household prefab the job: - skips dynamic household prefabs, - assigns initial money, - spawns citizens based on the household prefab data (students, adults, children, elders) and sets Citizen flags (Tourist / Commuter), - spawns household pets probabilistically, - potentially creates personal cars for the household based on outside-connection/road availability and household size, - assigns seeker components (LodgingSeeker for tourists, PropertySeeker otherwise), - enqueues tourist income statistics when relevant, - removes the CurrentBuilding component once initialization is complete.

The system uses a ModificationBarrier4 command buffer (parallel writer) to safely create entities and add/remove components from inside a job. It also coordinates with CityStatisticsSystem and a PersonalCarSelectData helper for vehicle creation.


Fields

  • private Unity.Entities.EntityQuery m_CarPrefabGroup
    Provides an entity query for car prefabs used by PersonalCarSelectData to choose vehicles for households.

  • private Unity.Entities.EntityQuery m_CitizenPrefabGroup
    Query used to gather citizen prefabs and their archetype data. These prefabs are sampled to spawn household members.

  • private Unity.Entities.EntityQuery m_HouseholdPetPrefabGroup
    Query used to gather household pet prefabs and their archetype data for pet spawning.

  • private Unity.Entities.EntityQuery m_Additions
    The main query that triggers this system's update. Matches entities with Household, PrefabRef, HouseholdCitizen, CurrentBuilding, Resources buffer and excludes Temp. RequireForUpdate is called with this query.

  • private ModificationBarrier4 m_EndFrameBarrier
    A modification barrier (command buffer) used to record entity creation and component changes from the job. The system creates a parallel writer and registers the job handle with the barrier.

  • private CityStatisticsSystem m_CityStatisticsSystem
    Reference to the CityStatisticsSystem used to get a safe statistics queue where tourist income events are enqueued.

  • private CityConfigurationSystem m_CityConfigurationSystem
    Reference to city configuration used by PersonalCarSelectData.PreUpdate.

  • private PersonalCarSelectData m_PersonalCarSelectData
    Helper used to select / create personal cars for households. It is prepared in PreUpdate() and finalized in PostUpdate() and interacts with the car prefab query.

  • private TypeHandle __TypeHandle
    Holds EntityTypeHandle, ComponentTypeHandle and ComponentLookup handles used by the job. Assigned in OnCreateForCompiler.

Properties

  • (None public)
    This system does not expose public properties. Its behavior is driven by entity queries and internal fields.

Constructors

  • public HouseholdInitializeSystem()
    Default constructor (annotated with [Preserve] on lifecycle methods). Typical Unity ECS system construction; real initialization occurs in OnCreate().

Methods

  • protected override void OnCreate()
    Sets up queries and subsystem references:
  • obtains a ModificationBarrier4 via World.GetOrCreateSystemManaged,
  • gets CityStatisticsSystem and CityConfigurationSystem,
  • constructs PersonalCarSelectData and prepares queries for cars, citizen prefabs and pet prefabs,
  • builds the m_Additions entity query and calls RequireForUpdate(m_Additions). This is where the system registers the queries and dependencies needed for its job.

  • protected override void OnUpdate()
    Main scheduling method. Prepares PersonalCarSelectData (PreUpdate) and schedules the InitializeHouseholdJob as a parallel IJobChunk using JobChunkExtensions.ScheduleParallel:

  • passes in handles/lookups and lists (citizen/pet prefabs, archetypes) via asynchronous ToEntityListAsync / ToComponentDataListAsync calls,
  • uses CityStatisticsSystem.GetSafeStatisticsQueue to get a safe queue and its dependency,
  • constructs a RandomSeed for randomized spawning,
  • schedules the job against the m_Additions query and combines dependencies,
  • hands the produced job handle to m_EndFrameBarrier and registers CityStatisticsSystem as a writer,
  • calls PersonalCarSelectData.PostUpdate(jobHandle) to finalize vehicle selection. This method ensures the job runs safely and integrates produced changes back into the world.

  • protected override void OnCreateForCompiler()
    Internal helper invoked by generated/compiled code to assign query and component handles for the job. Calls __AssignQueries and __TypeHandle.__AssignHandles.

  • private void __AssignQueries(ref SystemState state)
    Generated method; currently a placeholder that ensures query builder initialization (used by OnCreateForCompiler). Not typically used directly by modders.

Nested types and job details

  • InitializeHouseholdJob : IJobChunk (private, BurstCompile)
    The core job that runs in parallel over matching chunks. Key members and behavior:
  • Fields: EntityTypeHandle, ComponentTypeHandle, BufferTypeHandle, ComponentTypeHandle, ComponentTypeHandle, ComponentTypeHandle, ComponentTypeHandle, ComponentLookup, ComponentLookup, ComponentLookup, ComponentLookup, ComponentLookup, NativeList citizen & pet prefabs, NativeLists of ArchetypeData, PersonalCarSelectData, RandomSeed, CityStatisticsSystem.SafeStatisticQueue, and an EntityCommandBuffer.ParallelWriter.
  • Execute(...) iterates each matching entity (household) and:
    • reads prefab to lookup HouseholdData,
    • adds initial money (special handling for tourist households),
    • spawns citizens via SpawnCitizen (creates entity from random citizen prefab, assigns PrefabRef, HouseholdMember, Citizen (age/birthDay and flags), and CurrentBuilding),
    • spawns pets via SpawnHouseholdPet (similar pattern),
    • when outside-connection/road present and transform available, uses PersonalCarSelectData.CreateVehicle to create a vehicle and assigns Owner + OwnedVehicle buffer to the household,
    • randomizes household.m_Resources,
    • for tourist households: sets TouristHousehold component, adds LodgingSeeker and enqueues tourist income statistic,
    • for non-commuter households: adds PropertySeeker,
    • removes CurrentBuilding from the initialized household entity.
  • Helper methods:
    • SpawnCitizen(...) — creates a citizen entity from a randomly selected citizen prefab/archetype and sets up PrefabRef, HouseholdMember, Citizen (birthDay and flags), and adds CurrentBuilding.
    • SpawnHouseholdPet(...) — creates a household pet entity and sets PrefabRef, HouseholdPet component and CurrentBuilding.
  • Threading notes: uses EntityCommandBuffer.ParallelWriter for thread-safe entity modifications. Random uses RandomSeed per-chunk seed to avoid shared RNG issues. The job reads many ComponentLookups (isReadOnly) and uses NativeList data produced asynchronously; the OnUpdate() schedules and combines dependencies accordingly.

  • TypeHandle (private struct)
    Container for all EntityTypeHandle, ComponentTypeHandle and ComponentLookup handles required by the job, with a __AssignHandles method to populate them from a SystemState. This is generated-style plumbing used to pass handles into the job.

Usage Example

// Example: create a household entity so HouseholdInitializeSystem will initialize it next update.
// This would typically run inside another system or a MonoBehaviour that has access to a World/EntityManager.
var em = World.DefaultGameObjectInjectionWorld.EntityManager;
var system = World.DefaultGameObjectInjectionWorld.GetOrCreateSystemManaged<Game.Citizens.HouseholdInitializeSystem>();

// Suppose `householdPrefabEntity` is an Entity that represents a household prefab (with HouseholdData, ArchetypeData, etc.)
// and `buildingEntity` is the building where the household is currently placed.
Entity household = em.CreateEntity();
em.AddComponentData(household, new Game.Prefabs.PrefabRef { m_Prefab = householdPrefabEntity });
em.AddBuffer<Game.Economy.Resources>(household); // give it a resources buffer
em.AddComponentData(household, new Game.Citizens.Household()); // empty household component
em.AddComponentData(household, new Game.Citizens.HouseholdCitizen()); // household citizen buffer
em.AddComponentData(household, new Game.Citizens.CurrentBuilding { m_CurrentBuilding = buildingEntity });

// On the next tick, HouseholdInitializeSystem will pick up that entity (via m_Additions query) and perform:
// - resource assignment,
// - citizen/pet spawning,
// - possible vehicle creation,
// - adding seeker components and statistics as needed,
// - removing CurrentBuilding to mark initialization complete.

Notes for modders - To have a household initialized by this system, create an entity matching the m_Additions query: PrefabRef (pointing to a valid household prefab), Household component, HouseholdCitizen buffer, CurrentBuilding, and an Economy.Resources buffer. The system will handle the rest in its scheduled job. - The system relies on prefab data (HouseholdData, ArchetypeData, Citizen/HouseholdPet prefabs) being present in the world. Use the same prefab queries used by the game or register your prefabs similarly. - Changes are made via a parallel command buffer and are scheduled; to ensure downstream systems see results you must respect the system dependencies (the system registers its job handle with m_EndFrameBarrier and CityStatisticsSystem). - Randomness is chunk-seeded; don't assume deterministic order across different chunk layouts.