Game.CountHouseholdDataSystem
Assembly:
Namespace: Game.Simulation
Type: class
Base: GameSystemBase, IDefaultSerializable, ISerializable
Summary:
CountHouseholdDataSystem is a simulation system used to aggregate household- and citizen-related statistics every update interval. It scans household entities (including special households such as commuters, tourists and homeless), accumulates resource needs per household, computes population and average citizen metrics, tracks employable citizens by education level, and triggers unlock events based on citizen-related requirements. The system uses Unity ECS jobs (burst-compatible) and NativeAccumulators to perform work in parallel and exposes the latest aggregated results for other systems and UI/debug code.
Fields
-
private ResourceSystem m_ResourceSystem
Holds a reference to the global resource system (used for resource-related context; not heavily used directly in this file but available for resource logic). -
private CitySystem m_CitySystem
Reference to the CitySystem to obtain the city entity used when writing Population component data. -
private EndFrameBarrier m_EndFrameBarrier
Barrier used to create command buffers for producing unlock event entities at end-of-frame. -
private EntityQuery m_HouseholdQuery
EntityQuery that matches household entities to be processed by the CountHouseholdJob. -
private EntityQuery m_RequirementQuery
EntityQuery that matches prefabs/requirements to be processed by the CitizenRequirementJob. -
private EntityArchetype m_UnlockEventArchetype
Archetype used for creating unlock event entities (Event + Unlock components). -
private JobHandle m_HouseholdDataWriteDependencies
JobHandle that tracks the write dependencies for household aggregate data; used by readers to know when they must wait. -
private JobHandle m_HouseholdDataReadDependencies
Accumulated read dependencies from other systems that need to be combined before finalizing results. -
private NativeAccumulator<HouseholdData> m_HouseholdCountData
Accumulator for aggregated HouseholdData across all chunks (parallel writer used by CountHouseholdJob). -
private NativeAccumulator<HouseholdNeedData> m_HouseholdNeedCountData
Accumulator for aggregated household resource needs indexed by resource (parallel writer used in job). -
private HouseholdData m_LastHouseholdCountData
Snapshot of the last aggregated HouseholdData (kept on main thread for queries/debug). -
private NativeArray<int> m_ResourceNeed
Array storing accumulated resource needs per resource index. Length = EconomyUtils.ResourceCount. -
private bool m_NeedForceCountData
Flag set during deserialization when saved data is too old and a forced full count is required (OnUpdate completes dependency). -
private NativeArray<int> m_EmployableByEducation
Array of length 5 storing number of employable citizens for each education level (0..4). -
private TypeHandle __TypeHandle
Internal container of ComponentTypeHandle/BufferTypeHandle/ComponentLookup handles used to set up job accesses.
Properties
-
public int MovingInHouseholdCount
Number of households currently in a "moving in" state (value from last snapshot). -
public int MovingInCitizenCount
Number of citizens currently moving in (value from last snapshot). -
public int MovingAwayHouseholdCount
Number of households moving away (value from last snapshot). -
public int CommuterHouseholdCount
Number of commuter households (value from last snapshot). -
public int TouristCitizenCount
Number of tourist citizens currently in tourist households (value from last snapshot). -
public int HomelessHouseholdCount
Number of homeless households (value from last snapshot). -
public int HomelessCitizenCount
Number of homeless citizens (value from last snapshot). -
public int MovedInHouseholdCount
Number of households that are moved in (value from last snapshot). -
public int MovedInCitizenCount
Number of citizens that are moved in (value from last snapshot). -
public int ChildrenCount
Total child citizens (value from last snapshot). -
public int AdultCount
Total adult citizens (value from last snapshot). -
public int TeenCount
Total teen citizens (value from last snapshot). -
public int SeniorCount
Total senior (elderly) citizens (value from last snapshot). -
public int StudentCount
Total citizens flagged as students (value from last snapshot). -
public int UneducatedCount
Count of citizens at education level 0 (value from last snapshot). -
public int PoorlyEducatedCount
Count of citizens at education level 1 (value from last snapshot). -
public int EducatedCount
Count of citizens at education level 2 (value from last snapshot). -
public int WellEducatedCount
Count of citizens at education level 3 (value from last snapshot). -
public int HighlyEducatedCount
Count of citizens at education level 4 (value from last snapshot). -
public int WorkableCitizenCount
Count of citizens considered "workable" (eligible to work; excludes students, sick, dead, etc.) (value from last snapshot). -
public int CityWorkerCount
Count of citizens that are city workers (work locally, not outside connections) (value from last snapshot). -
public int DeadCitizenCount
Number of dead citizens found in households (value from last snapshot). -
public int AverageCitizenHappiness
Average happiness among moved-in citizens (derived from last snapshot; 0 if no moved-in citizens). -
public int AverageCitizenHealth
Average health among moved-in citizens (derived from last snapshot; 0 if no moved-in citizens). -
public float UnemploymentRate
Unemployment rate computed from last snapshot: percent of workable citizens without local city jobs. -
public float HomelessnessRate
Percent of moved-in citizens that are homeless (derived from last snapshot).
Constructors
public CountHouseholdDataSystem()
Default constructor (empty, required by ECS/serialization). System initialization happens in OnCreate.
Methods
-
public override int GetUpdateInterval(SystemUpdatePhase phase)
Returns the system's update interval in ticks. The system uses an interval of 16 (runs every 16 ticks). -
public HouseholdData GetHouseholdCountData()
Returns the last snapshot of aggregated HouseholdData (m_LastHouseholdCountData). -
public NativeArray<int> GetResourceNeeds(out JobHandle deps)
Returns the NativeArray for resource needs and outputs a JobHandle (deps) representing current write dependencies. Callers must respect deps before reading the array (complete or combine appropriately). -
public bool IsCountDataNotReady()
Returns true if the system flagged that a forced full count is required (set during older-save deserialization). -
public NativeArray<int> GetEmployables()
Returns the array of employable-by-education counts (length 5). -
public void AddHouseholdDataReader(JobHandle reader)
Allows other systems to add their read dependency so the system can combine them before finalizing the ResultJob. Use this to register jobs that read aggregated household data. -
protected override void OnCreate()
Initializes queries, allocates NativeAccumulator and NativeArray buffers, creates archetypes and references to other systems. Also calls RequireForUpdate(m_HouseholdQuery) so the system only updates when households exist. -
protected override void OnDestroy()
Disposes NativeAccumulator and NativeArray allocations and performs cleanup. -
public void Serialize<TWriter>(TWriter writer) where TWriter : IWriter
Serializes the last snapshot data, resource needs, and employable counts to writer. -
public void Deserialize<TReader>(TReader reader) where TReader : IReader
Deserializes snapshot and arrays; handles format/version compatibility and sets m_NeedForceCountData if stored data is too old to trust. -
public void SetDefaults(Context context)
Resets the last snapshot and clears accumulators and arrays (used on new game or when context requires reinitialization). -
protected override void OnUpdate()
Main update routine: - Copies last snapshot from the current accumulators and clears accumulators for the next run.
- Schedules CountHouseholdJob in parallel across the household query to accumulate HouseholdData and HouseholdNeedData.
- Schedules ResultJob to read accumulators and write Population and fill the m_ResourceNeed and m_EmployableByEducation arrays.
- If a forced count is required (from deserialization), the system completes dependencies immediately.
- Schedules CitizenRequirementJob in parallel across requirement prefabs to update unlock progress and produce unlock events, using the EndFrameBarrier command buffer.
-
Adds the final dependency to EndFrameBarrier so created entities are produced safely.
-
protected override void OnCreateForCompiler()
Internal setup for ECS code generation / compiler-time helpers; assigns type handles and queries. -
private void __AssignQueries(ref SystemState state)
Internal helper used by the generated OnCreateForCompiler; stubbed in source (keeps query assignment consistent for the compiler). -
Internal job structs (Burst-compiled):
CountHouseholdJob : IJobChunk
— iterates household chunks and produces per-chunk HouseholdData and per-resource HouseholdNeedData into parallel NativeAccumulators.ResultJob : IJob
— collects final results from accumulators, writes Population component and fills arrays for resource needs and employable-by-education counts.CitizenRequirementJob : IJobChunk
— evaluates CitizenRequirementData against current Population values and creates unlock events when requirements are met.
Usage Example
// Example: reading the latest resource needs from CountHouseholdDataSystem
var world = World.DefaultGameObjectInjectionWorld;
var countSystem = world.GetOrCreateSystemManaged<Game.Simulation.CountHouseholdDataSystem>();
// Ask the system for the resource needs array and get the dependency handle
JobHandle deps;
NativeArray<int> resourceNeeds = countSystem.GetResourceNeeds(out deps);
// Ensure any scheduled jobs producing the data are finished before reading
deps.Complete();
// Read a resource need (index corresponds to EconomyUtils resource index)
int foodNeedIndex = EconomyUtils.GetResourceIndex(Resource.Food);
int foodNeed = resourceNeeds[foodNeedIndex];
UnityEngine.Debug.Log($"Food need: {foodNeed}");
Notes: - When reading NativeArray data returned by GetResourceNeeds/GetEmployables you must respect the returned JobHandle (deps) to avoid race conditions. - The system exposes many debug-watchable properties (counts and rates) which are read-only and reflect the last aggregated snapshot.