Skip to content

Game.Creatures.InitializeSystem

Assembly: Game (runtime assembly for game systems)
Namespace: Game.Creatures

Type: class

Base: GameSystemBase

Summary: System responsible for initializing newly updated creature entities (humans and animals) at the beginning of their lifecycle/update. It schedules the Burst-compiled IJobChunk InitializeCreaturesJob which: - Calculates and sets initial transforms and navigation targets for Human and Animal entities. - Positions creatures relative to their path or spawn locations (including buildings and area spawn triangles). - Initializes lane state (positions, flags) respecting left-/right-hand traffic, swimming behavior and roaming. - Applies per-creature flags such as Cold and Homeless based on climate and household/resident data. - Removes TripSource/Unspawned components when the source is deleted. - Uses lookups for many game components (prefabs, spawn locations, area geometry, building data) and writes commands through a ModificationBarrier (EntityCommandBuffer). This system runs only when Creature entities are marked Updated.


Fields

  • private ModificationBarrier5 m_ModificationBarrier
    {{ The modification barrier is used to create an EntityCommandBuffer. The system writes structural changes (e.g. removing TripSource components) via the barrier's command buffer to safely mutate entities from a job. }}

  • private CityConfigurationSystem m_CityConfigurationSystem
    {{ Reference to the city configuration system. Used to query city-wide settings such as leftHandTraffic which affects lane position calculations. }}

  • private ClimateSystem m_ClimateSystem
    {{ Reference to the climate system. The system samples m_ClimateSystem.temperature to determine whether humans should get the Cold flag. }}

  • private EntityQuery m_CreatureQuery
    {{ Query used to select creature entities that need initialization. The system RequiresForUpdate on this query so it runs only when such entities are present/updated. }}

  • private ComponentTypeSet m_TripSourceRemoveTypes
    {{ A ComponentTypeSet containing TripSource and Unspawned used to quickly remove trip-related components (via command buffer) when their source is deleted. }}

  • private TypeHandle __TypeHandle
    {{ Internal helper struct that holds all Entity/Component/Buffer handles and ComponentLookup/BufferLookup instances. It's assigned during OnCreateForCompiler to allow fast handle access in jobs. }}

  • private struct InitializeCreaturesJob (nested)
    {{ The Burst-compiled IJobChunk that performs the bulk of initialization work on chunks of creature entities. It reads/writes many component arrays and lookups, handles spawn location selection, path transform calculation, navigation setup, lane initialization, and flags such as Cold, Homeless, Swimming. Contains helper methods: CalculatePathTransform, HasAuthorization, FindClosestSpawnLocation. }}

  • private struct TypeHandle (nested)
    {{ Encapsulates EntityTypeHandle, ComponentTypeHandles, BufferTypeHandles and ComponentLookup/BufferLookup members used by the job. Provides __AssignHandles(ref SystemState) to initialize handles from the system state. }}


Properties

  • None.
    {{ This system does not expose public properties. All configuration and lookups are internal fields and local job data. }}

Constructors

  • public InitializeSystem()
    {{ Default (parameterless) constructor. Systems in the game's ECS are created by the World/Bootstrap; no custom initialization is performed in the constructor beyond what GameSystemBase provides. }}

Methods

  • protected override void OnCreate()
    {{ Initializes internal references: obtains ModificationBarrier5, CityConfigurationSystem and ClimateSystem; builds the EntityQuery for Creature + Updated; sets up the ComponentTypeSet used to remove trip source related components; calls RequireForUpdate to ensure the system only runs when creatures are present/updated. }}

  • protected override void OnUpdate()
    {{ Creates and populates the InitializeCreaturesJob with the current ComponentTypeHandles, ComponentLookups, BufferLookups, a RandomSeed, temperature and leftHandTraffic settings, and a parallel EntityCommandBuffer. Schedules the job in parallel over m_CreatureQuery and registers its dependency with the modification barrier. This is the runtime entry point that triggers the parallel initialization work. }}

  • protected override void OnCreateForCompiler()
    {{ Internal helper called by the generated code path: calls __AssignQueries and TypeHandle.__AssignHandles to pre-initialize query/handle state needed by the job when compiled/iterated by the runtime. }}

  • private void __AssignQueries(ref SystemState state)
    {{ Currently creates (and immediately disposes) an EntityQueryBuilder(Allocator.Temp) — placeholder in the compiled source. The primary handle assignment occurs in TypeHandle.__AssignHandles. }}

  • private struct TypeHandle.__AssignHandles(ref SystemState state)
    {{ Assigns all Entity/Component/Buffer type handles and ComponentLookup/BufferLookup instances from the provided SystemState. This prepares handles used when constructing the job. }}

Nested InitializeCreaturesJob methods (important behaviour summary):

  • void InitializeCreaturesJob.Execute(in ArchetypeChunk chunk, int unfilteredChunkIndex, bool useEnabledMask, in v128 chunkEnabledMask)
    {{ Main chunk-processing function. For each chunk it:

    • Retrieves arrays/buffers (Entity, Human, Animal, Navigation, CurrentVehicle, PathOwner, etc.).
    • If HumanNavigation components exist: sets target position/direction from current transform or path transform; handles exiting vehicles and end-of-path actions.
    • Initializes Human flags: clears Cold/Homeless and sets Cold if climate temperature < per-entity or pseudo-random threshold; checks resident/household/renter data to set Homeless.
    • Initializes HumanCurrentLane: sets lane flags depending on whether lane is a transform target or connection/area; computes lane position randomized (squared distribution) and flips based on leftHandTraffic and backward flags.
    • For animals: sets lane flags similarly, sets Swimming flags (if move speed is zero and swim speed > 0), sets roaming positions, and adjusts Y position for swim depth if applicable.
    • Handles TripSource/Unspawned: if the source entity is deleted, removes TripSource/Unspawned from creature; if spawn locations exist, finds the closest or random spawn location (using FindClosestSpawnLocation) and adjusts the creature's transform position/rotation accordingly.
    • Writes out HumanNavigation and AnimalNavigation targets based on final transform.
    • Uses m_CommandBuffer (parallel) to perform structural removals when needed. The method makes extensive use of ComponentLookup, BufferLookup and RandomSeed for deterministic/randomized initialization. }}
  • private Transform CalculatePathTransform(Entity creature, PathOwner pathOwner, DynamicBuffer<PathElement> path)
    {{ If the creature has a path and the pathOwner's element index points inside it and the target element references a Curve, this computes the transform along that curve (position and forward rotation) using the curve's bezier and tangent. Otherwise returns the creature's current transform. Used to orient creatures along their path when spawning or at initialization. }}

  • private bool HasAuthorization(Entity entity, Entity building)
    {{ Checks whether the given entity (via Resident -> HouseholdMember or Worker data) has authorization to spawn/use a building (property renter or workplace matching the building). Returns true if authorized. Used by FindClosestSpawnLocation to bias random spawn selection based on authorization requirement. }}

  • private bool FindClosestSpawnLocation(float3 comparePosition, out float3 spawnPosition, DynamicBuffer<SpawnLocationElement> spawnLocations, bool randomLocation, ref Random random, bool hasAuthorization)
    {{ Iterates spawn locations attached to a building/prefab. For each spawn location element of type SpawnLocation or HangaroundLocation and with pedestrian connection type:

    • If a direct transform exists for the spawn location, it uses its position (or a randomized metric if randomLocation is true) to select the best spawn point.
    • Otherwise it enumerates area triangles and finds a point in the triangle (either by distance to comparePosition or by randomized barycentric sampling when randomLocation is true).
    • The method prefers spawn locations whose SpawnLocationData has an activity mask (m_ActivityMask) when appropriate.
    • Returns true if a spawn position was selected; otherwise false. This function is used to find appropriate initial spawn coordinates for creatures relative to their TripSource. }}

Usage Example

// Example usage inside another system or initialization code.
// Typically the game's world will create and update this system automatically,
// but you can get or reference it from the World if needed.

using Unity.Entities;
using Game.Creatures;

[Preserve]
public class ExampleUsageSystem : GameSystemBase
{
    protected override void OnCreate()
    {
        base.OnCreate();
        // Ensure the InitializeSystem exists (will be created if missing)
        var initSystem = World.GetOrCreateSystemManaged<InitializeSystem>();
        // You can query related systems/settings used by InitializeSystem:
        var cityConfig = World.GetOrCreateSystemManaged<CityConfigurationSystem>();
        bool leftHand = cityConfig.leftHandTraffic;
    }

    protected override void OnUpdate()
    {
        // The InitializeSystem schedules its jobs in its own OnUpdate.
    }
}

Notes: - The initialization job is Burst-compiled and scheduled in parallel for performance — avoid accessing managed objects inside component lookups used by the job. - The system relies on many game-specific component types (TripSource, SpawnLocationData, Curve, BuildingData, AnimalData, etc.), so it should be used in the game runtime context where those components exist.