Skip to content

Game.CountStudyPositionsSystem

Assembly: Game
Namespace: Game.Simulation

Type: class

Base: GameSystemBase, IDefaultSerializable, ISerializable

Summary:
CountStudyPositionsSystem is an ECS system used to count available study positions (vacant student slots) across all school buildings in the game, grouped by education level. It runs on a regular interval (every 16 updates) and schedules a Burst-compiled IJob (CountStudyPositionsJob) that iterates school archetype chunks. The job reads prefab references, student buffers, installed upgrades, and school prefab data; it ignores outside-connection prefabs and applies installed upgrades to building stats before calculating the vacant study positions. Results are stored in a persistent NativeArray of length 5 (one slot per education level). The system exposes the array for other systems via GetStudyPositionsByEducation and provides mechanisms to register readers for proper job dependency tracking. It also implements serialization so the counts can be saved/loaded.


Fields

  • private EntityQuery m_SchoolQuery
    Holds an entity query that selects school building entities. The query requires Building, School, Student buffer and PrefabRef components and excludes OutsideConnection, Temp, Destroyed and Deleted components.

  • private NativeArray<int> m_StudyPositionByEducation
    A persistent NativeArray of length 5 containing the number of available study positions per education level (index = education level). Marked with DebugWatchValue. Allocated in OnCreate and disposed in OnDestroy.

  • private JobHandle m_WriteDependencies
    JobHandle representing the write dependency for consumers of the study position array. Updated after scheduling the counting job in OnUpdate.

  • private JobHandle m_ReadDependencies
    JobHandle that accumulates registered reader dependencies via AddReader. Combined with the system's dependencies when scheduling the counting job to preserve correct ordering.

  • private TypeHandle __TypeHandle
    Internal container of ComponentTypeHandle / BufferTypeHandle / ComponentLookup instances used for resolving component access in jobs and during compilation-time setup. Populated in OnCreateForCompiler.

  • private struct CountStudyPositionsJob (nested)
    Burst-compiled IJob that performs the actual counting. Reads archetype chunks from the school query, iterates entities and buffers, optionally applies installed upgrades, and increments the counters in m_StudyPositionByEducation. It obtains component lookups for prefab data and school data to determine capacities and education levels.

  • private struct TypeHandle (nested)
    Internal helper struct that stores readonly handles/lookup fields and provides __AssignHandles to initialize them from a SystemState.

Properties

  • (none)
    This system does not expose C# properties. It exposes results via the GetStudyPositionsByEducation method (see Methods).

Constructors

  • public CountStudyPositionsSystem()
    Default constructor. No special runtime initialization beyond what OnCreate does.

Methods

  • public override int GetUpdateInterval(SystemUpdatePhase phase)
    Returns 16. The system is scheduled to update every 16 simulation update frames.

  • public NativeArray<int> GetStudyPositionsByEducation(out JobHandle deps)
    Returns the internal NativeArray (m_StudyPositionByEducation) and outputs the current write JobHandle in deps (m_WriteDependencies). Callers should use the returned JobHandle to ensure they read the array only after the counting job has completed (or add it to their own dependency tracking).

  • public void AddReader(JobHandle reader)
    Registers a reader JobHandle by combining it into m_ReadDependencies. This ensures the system will wait for all readers when scheduling its writing job to avoid race conditions.

  • protected override void OnCreate()
    Initializes the entity query for schools and allocates m_StudyPositionByEducation as a persistent NativeArray(5). Called when the system is created.

  • protected override void OnDestroy()
    Disposes m_StudyPositionByEducation and calls base.OnDestroy(). Ensures persistent native memory is released.

  • public void SetDefaults(Context context)
    Resets the m_StudyPositionByEducation array to zero for all five education levels. Used by the serialization/defaulting system.

  • public void Serialize<TWriter>(TWriter writer) where TWriter : IWriter
    Writes the m_StudyPositionByEducation array to the provided writer for saving.

  • public void Deserialize<TReader>(TReader reader) where TReader : IReader
    Reads values into m_StudyPositionByEducation. Handles backward compatibility: if the saved version is older than Version.economyFix, it reads and discards a single int and returns early; otherwise it reads 5 ints into the native array.

  • protected override void OnUpdate()
    Constructs and schedules CountStudyPositionsJob:

  • Obtains an asynchronous archetype chunk list for the school query (ToArchetypeChunkListAsync) using the world update allocator, producing an outJobHandle.
  • Fills job fields including component type/buffer handles and component lookups (via InternalCompilerInterface and the __TypeHandle).
  • Schedules the job using IJobExtensions.Schedule and combines base.Dependency, m_ReadDependencies and the outJobHandle to preserve dependencies.
  • Stores the resulting JobHandle into m_WriteDependencies so consumers can wait on it.

  • protected override void OnCreateForCompiler()
    Called during compile-time wiring: assigns queries and initializes the __TypeHandle handles using the SystemState reference.

  • private void __AssignQueries(ref SystemState state)
    Currently contains an EntityQueryBuilder Temp creation and Dispose; placeholder for query assignment used by compiler-generated code.

Usage Example

// Example: read the current counts of available study positions safely from another system.
public void SomeConsumerMethod(CountStudyPositionsSystem countSystem)
{
    // Get the array and the JobHandle to wait on
    JobHandle writeDeps;
    NativeArray<int> studyByEdu = countSystem.GetStudyPositionsByEducation(out writeDeps);

    // If running on the main thread, ensure the counting job completed before reading:
    writeDeps.Complete();

    // Read values (indices 0..4 correspond to education levels)
    for (int edu = 0; edu < studyByEdu.Length; ++edu)
    {
        int availableSlots = studyByEdu[edu];
        // use availableSlots...
    }

    // If this consumer itself schedules jobs that will read the array,
    // register them with AddReader so the counter system waits when next updating:
    // countSystem.AddReader(myJobHandle);
}