Game.Objects.ObjectEmergeSystem
Assembly: Assembly-CSharp
Namespace: Game.Objects
Type: class
Base: GameSystemBase
Summary:
ObjectEmergeSystem is a world/system-level ECS system responsible for handling "emergence" of in-game objects (creatures, pets, citizens and similar) when their containing vehicle or building is deleted/unspawned. It scans deleted buildings and vehicles, collects entities (citizens, pets, passengers, spawnable object proxies) that should "emerge" into the world, and then performs the required component removals/additions and spawns new object entities (resident creature objects, pets, or put humans/animals into navigation lanes). The system is implemented with Unity DOTS patterns: entity queries, IJobChunk jobs, IJob, NativeQueue, EntityCommandBuffer via a ModificationBarrier4B, and uses many ComponentLookup / ComponentTypeHandle accesses for read-only data. It also exposes static helper methods used to select appropriate creature/pet prefabs based on probabilistic selection and citizen attributes.
Fields
-
private ModificationBarrier4B m_ModificationBarrier
Used to obtain an EntityCommandBuffer to issue structural changes (add/remove components, create entities) safely from jobs. This barrier is used to defer changes until it's safe to apply them. -
private EntityQuery m_DeletedBuildingQuery
Query matching deleted building entities (Deleted + Building, excluding Temp). Used to find buildings whose occupants should emerge. -
private EntityQuery m_DeletedVehicleQuery
Query matching deleted vehicle entities (Deleted + Passenger buffer, excluding Temp). Used to find vehicles whose passengers should emerge. -
private EntityQuery m_EmergeObjectQuery
Query that matches entities that can be considered for emergence (any of CurrentBuilding or TripSource, excluding Deleted and Temp). Used by the find-jobs to scan potential emerge-able objects. -
private EntityQuery m_CreaturePrefabQuery
Query matching creature prefabs (CreatureData + PrefabData). Used to collect prefab chunks for random selection of spawn prefabs. -
private ComponentTypeSet m_TripSourceRemoveTypes
ComponentTypeSet describing components to remove from TripSource entities when they emerge (TripSource, Unspawned). Used with CommandBuffer.RemoveComponent with a type set. -
private ComponentTypeSet m_CurrentVehicleRemoveTypes
ComponentTypeSet describing components to remove from CurrentVehicle entities when they exit a vehicle (CurrentVehicle, Relative, Unspawned). -
private ComponentTypeSet m_CurrentVehicleHumanAddTypes
Type set describing components to add to humans when they exit a vehicle (Moving, TransformFrame, InterpolatedTransform, HumanNavigation, HumanCurrentLane, Blocker, Updated). -
private ComponentTypeSet m_CurrentVehicleAnimalAddTypes
Type set describing components to add to animals when they exit a vehicle (Moving, TransformFrame, InterpolatedTransform, AnimalNavigation, AnimalCurrentLane, Blocker, Updated). -
private ComponentTypeSet m_HumanSpawnTypes
Type set for newly created human/resident objects (HumanCurrentLane, TripSource, Unspawned, Divert). -
private ComponentTypeSet m_AnimalSpawnTypes
Type set for newly created animal objects (AnimalCurrentLane, TripSource, Unspawned). -
private TypeHandle __TypeHandle
Internal struct storing EntityTypeHandle, ComponentTypeHandle and ComponentLookup handles used by the jobs. It has a helper to assign handles from a SystemState.
Properties
- None public.
ObjectEmergeSystem does not expose public properties; all state is private and the system is driven by world updates and entity queries.
Constructors
public ObjectEmergeSystem()
Default constructor (marked with [Preserve] for AOT/IL2CPP). The system initialization logic is in OnCreate.
Methods
protected override void OnCreate()
Initializes queries, type sets and obtains the ModificationBarrier4B. Sets up:- m_DeletedBuildingQuery
- m_DeletedVehicleQuery
- m_EmergeObjectQuery
- m_CreaturePrefabQuery
-
All ComponentTypeSet definitions for add/remove operations This is where the system registers what it will operate on and prepares the barrier to apply structural changes.
-
protected override void OnUpdate()
Main runtime logic executed each frame (or system update). Key steps: - Check whether there are any deleted buildings or deleted vehicles to process; if none, return early.
- Create a NativeQueue
(emergeQueue) to collect entities that must emerge. - If buildings are deleted: iterate deleted building archetype chunks, schedule FindObjectsInBuildingJob for each deleted building to enqueue occupants (CurrentBuilding or TripSource referencing that building).
- If vehicles are deleted: schedule FindObjectsInVehiclesJob on deleted vehicles to enqueue passengers.
- Gather creature prefab chunks (m_CreaturePrefabQuery) asynchronously.
- Schedule EmergeObjectsJob which dequeues entities, and for each:
- If entity has TripSource: remove TripSource/unspawned types and mark updated.
- Else if entity has CurrentVehicle: call internal ExitVehicle logic to remove CurrentVehicle and add movement/navigation components for humans/animals.
- Else if entity has CurrentBuilding: call ExitBuilding logic which may spawn resident objects or pets (SpawnResident/SpawnPet).
-
Dispose of native containers via job dependencies and register job handle with modification barrier.
-
public static Entity SelectResidentPrefab(Citizen citizenData, NativeList<ArchetypeChunk> chunks, EntityTypeHandle entityType, ref ComponentTypeHandle<CreatureData> creatureType, ref ComponentTypeHandle<ResidentData> residentType, out CreatureData creatureData, out PseudoRandomSeed randomSeed)
Static helper that iterates creature-prefab chunks and selects an appropriate resident prefab based on the citizen's gender and age. Uses a pseudo-random selection process (weighted selection via SelectItem). Returns the prefab Entity and the matched CreatureData and a PseudoRandomSeed created from the citizen's pseudo-random source. -
public static Entity SelectAnimalPrefab(ref Random random, PetType petType, NativeList<ArchetypeChunk> chunks, EntityTypeHandle entityType, ComponentTypeHandle<PetData> petDataType, out PseudoRandomSeed randomSeed)
Selects an animal/pet prefab that matches a given PetType, using the provided Random. Returns chosen prefab Entity and outputs a PseudoRandomSeed for the spawn. -
private static bool SelectItem(ref Random random, int probability, ref int totalProbability)
Small helper used by the selection routines that performs incremental weighted selection (reservoir-like selection using accumulated total probability). -
private void __AssignQueries(ref SystemState state)
Internal method used by compiler-generated OnCreateForCompiler. Currently a placeholder that builds and disposes an EntityQueryBuilder (no-op in this compiled variation). -
protected override void OnCreateForCompiler()
Compiler helper that assigns queries and type handles when systems are compiled. Calls __AssignQueries and TypeHandle.__AssignHandles.
Nested job types (summaries):
-
FindObjectsInBuildingJob : IJobChunk
Scans a chunk for CurrentBuilding or TripSource components matching a specific building Entity; enqueues matching entities into the emerge queue. Used to find occupants of a deleted building. -
FindObjectsInVehiclesJob : IJobChunk
Iterates Passenger buffers on vehicle-related chunks and enqueues each passenger entity found into the emerge queue. Used to find passengers of deleted vehicles. -
EmergeObjectsJob : IJob
Dequeues collected entities and performs the actual emergence logic:- Converts TripSource entities into updated batches if needed (removes TripSource/Unspawned).
- Handles vehicle exits (ExitVehicle): removes CurrentVehicle, adds appropriate movement/navigation components depending on Human/Animal and sets lane info; sets Unspawned if vehicle was unspawned.
- Handles building exits (ExitBuilding): removes CurrentBuilding, and in case of citizens/pets may spawn new object entities using creature/pet prefabs. For citizens, it also sets TravelPurpose on the citizen (GoingHome or Leisure depending on household home).
Notes about EmergeObjectsJob implementation: - Uses many ComponentLookup<> to read components like Citizen, Human/Animal flags, Transform, PrefabRef, ObjectData, etc. - Uses an EntityCommandBuffer from m_ModificationBarrier to create entities and apply structural changes. - Uses m_CreaturePrefabChunks and the static selection helpers to pick spawn prefabs. - Takes care to set Resident flags (clearing InVehicle, resetting timer) when a resident emerges.
Usage Example
// Example: calling the static SelectAnimalPrefab helper (simplified).
// In real code you need valid NativeList<ArchetypeChunk>, EntityTypeHandle and PetData ComponentTypeHandle (from a SystemState).
Random random = new Random(12345);
NativeList<ArchetypeChunk> creaturePrefabChunks = /* obtained from a query: m_CreaturePrefabQuery.ToArchetypeChunkList(...) */;
EntityTypeHandle entityTypeHandle = /* obtained from system state */;
ComponentTypeHandle<PetData> petDataHandle = /* obtained from system state */;
PseudoRandomSeed seed;
Entity chosenPetPrefab = ObjectEmergeSystem.SelectAnimalPrefab(ref random, PetType.Dog, creaturePrefabChunks, entityTypeHandle, petDataHandle, out seed);
if (chosenPetPrefab != Entity.Null)
{
// chosenPetPrefab is a prefab entity (use ObjectData to get archetype) and seed can be used to set the spawned entity's PseudoRandomSeed.
}
Modding tips and cautions: - This system is tightly coupled with internal component types (CurrentBuilding, CurrentVehicle, TripSource, Passenger, PrefabRef, ObjectData, CreatureData, etc.). Be cautious when interacting with these components—changes to their semantics can break emergence behavior. - Structural changes are done through a ModificationBarrier4B and deferred via EntityCommandBuffer to avoid invalidating job reads/writes. - If you add new spawnable creature or pet prefabs, ensure they are picked up by m_CreaturePrefabQuery (they must have CreatureData or PetData and be marked as prefab data). - When scheduling custom jobs that interact with the same queries or components, respect the system's dependencies (base.Dependency) and the ModificationBarrier producer job handle to avoid race conditions. - The selection helpers use incremental totalProbability and Random.NextInt(totalProbability) to implement simple weighted selection; if you change probabilities you must maintain that logic or adjust selection accordingly.