Game.Prefabs.WorkVehicleSelectData
Assembly: Assembly-CSharp (game)
Namespace: Game.Prefabs
Type: struct
Base: System.ValueType
Summary:
WorkVehicleSelectData is a helper/value-type used by vehicle-spawning systems to select and create "work" vehicle prefabs (including combinations of tractors and trailers) based on a set of requirements (road type, size class, map features, resources, and custom requirement checks). It collects matching prefab archetype chunks (via an EntityQuery) and then iterates them to pick suitable vehicle prefab(s), optionally assembling multi-entity layouts (tractor + trailer chains). Selection uses a simple incremental probability pick (reservoir-like random selection) implemented in PickVehicle. PreUpdate / PostUpdate manage the asynchronous collection of matching archetype chunks.
Fields
-
private NativeList<ArchetypeChunk> m_PrefabChunks
Holds the list of prefab archetype chunks that match the entity query built from GetEntityQueryDesc(). Created in PreUpdate via query.ToArchetypeChunkListAsync and must be disposed via PostUpdate. This list is read when selecting prefabs in CreateVehicle/Check* methods. -
private VehicleSelectRequirementData m_RequirementData
Helper storing per-chunk precomputed requirement-check data (VehicleSelectRequirementData) used to filter prefabs by custom requirements (e.g., DLC/availability, city configuration). Constructed in the WorkVehicleSelectData constructor. -
private EntityTypeHandle m_EntityType
EntityTypeHandle used to read Entity values from chunks. Updated during PreUpdate. -
private ComponentTypeHandle<WorkVehicleData> m_WorkVehicleDataType
ComponentTypeHandle (read-only) for WorkVehicleData used to filter and inspect work-specific data on prefab entities. -
private ComponentTypeHandle<CarTrailerData> m_CarTrailerDataType
ComponentTypeHandle (read-only) for CarTrailerData used to identify trailer prefabs and trailer properties. -
private ComponentTypeHandle<CarTractorData> m_CarTractorDataType
ComponentTypeHandle (read-only) for CarTractorData used to identify tractor prefabs and tractor properties. -
private ComponentTypeHandle<CarData> m_CarDataType
ComponentTypeHandle (read-only) for CarData used to check car-specific properties (size class, etc.). -
private ComponentTypeHandle<WatercraftData> m_WatercraftDataType
ComponentTypeHandle (read-only) for WatercraftData used to check watercraft-specific properties (size class, etc.). -
private ComponentTypeHandle<ObjectData> m_ObjectDataType
ComponentTypeHandle (read-only) for ObjectData used to get the prefab archetype (ObjectData.m_Archetype) and other object-level metadata.
Properties
- (No public properties)
This struct exposes no public properties; interaction is via methods.
Constructors
public WorkVehicleSelectData(SystemBase system)
Initializes a new WorkVehicleSelectData instance. Registers and initializes the internal ComponentTypeHandle and EntityTypeHandle references and creates a VehicleSelectRequirementData initialized with the provided SystemBase for later requirement checks. Does not allocate the prefab chunk list — that happens in PreUpdate.
Methods
public static EntityQueryDesc GetEntityQueryDesc()
Returns an EntityQueryDesc configured to select prefab entities that should be considered as work vehicles:- All: WorkVehicleData (read-only), ObjectData (read-only), PrefabData (read-only)
- Any: CarData or WatercraftData (read-only)
-
None: Locked (read-only) Use this when creating an EntityQuery that you will pass to PreUpdate.
-
public void PreUpdate(SystemBase system, CityConfigurationSystem cityConfigurationSystem, EntityQuery query, Allocator allocator, out JobHandle jobHandle)
Collects matching prefab archetype chunks asynchronously into m_PrefabChunks by calling query.ToArchetypeChunkListAsync(allocator, out jobHandle). Also updates internal ComponentTypeHandle/EntityTypeHandle with the provided system and updates m_RequirementData based on the CityConfigurationSystem. The caller receives the JobHandle produced by ToArchetypeChunkListAsync and is responsible for ensuring the returned job completes before iterating m_PrefabChunks on the main thread (e.g., call jobHandle.Complete()).
Parameters: - system: the SystemBase used to update type handles. - cityConfigurationSystem: used to update m_RequirementData. - query: the EntityQuery (should be created with GetEntityQueryDesc()). - allocator: allocator to create the NativeList (commonly Allocator.TempJob). - jobHandle (out): the async handle that must be completed before using m_PrefabChunks.
-
public void PostUpdate(JobHandle jobHandle)
Disposes the internal m_PrefabChunks NativeList. Pass the same JobHandle returned from PreUpdate (or a completed JobHandle if you completed it) so disposal is scheduled correctly. After PostUpdate returns the m_PrefabChunks is no longer valid. -
public Entity CreateVehicle(EntityCommandBuffer.ParallelWriter commandBuffer, int jobIndex, ref Random random, RoadTypes roadTypes, SizeClass sizeClass, VehicleWorkType workType, MapFeature mapFeature, Resource resource, ref float workAmount, Transform transform, Entity source, WorkVehicleFlags state)
High-level selection routine. Iterates the previously populated m_PrefabChunks to find a suitable vehicle prefab (and optional attached tractors/trailers) that match the provided constraints: - roadTypes: allowed transport modes (Car, Watercraft).
- sizeClass: optional size constraint.
- workType: the intended work the vehicle will perform.
- mapFeature / resource: used to choose vehicles specialized for a map feature or resource.
- workAmount (in/out): the remaining work to assign to created vehicles; reduced by the work amount assigned to created vehicle(s).
- transform, source, state: used when creating runtime Vehicle entities. Selection supports multi-entity layouts: a primary vehicle (tractor or standalone) and up to three attached vehicles (trailers/tractors) — the algorithm checks compatibility constraints (trailer/tractor types and fixed pairings). Selection randomness is handled with PickVehicle which maintains a running totalProbability and does incremental random selection.
Returns: an Entity referencing the newly created runtime vehicle (Entity is created in the provided EntityCommandBuffer). If no suitable vehicle is found, returns Entity.Null and sets workAmount to 0.
Notes: - The method assumes m_PrefabChunks is valid and populated (call PreUpdate and ensure the returned JobHandle is completed prior to calling). - The created entity is initialized with Transform, WorkVehicle component, PrefabRef, PseudoRandomSeed, TripSource and Unspawned tag. If additional linked vehicles are created they are added to a LayoutElement buffer on the primary entity and have Controller set to the primary entity.
-
private Entity CreateVehicle(EntityCommandBuffer.ParallelWriter commandBuffer, int jobIndex, ref Random random, VehicleData data, VehicleWorkType workType, ref float workAmount, Transform transform, Entity source, WorkVehicleFlags state)
Lower-level helper that actually creates a single runtime vehicle entity from a chosen prefab (VehicleData). Sets WorkVehicle.m_WorkAmount based on requested work and prefab max; sets initial components (Transform, WorkVehicle, PrefabRef, PseudoRandomSeed, TripSource, Unspawned). Returns the created Entity. -
private CheckTrailers(...) [multiple overloads]
Several overloads exist to walk trailer prefabs and check compatibility when assembling trailer chains. Overloads differ in arity to support checking: - pairing a tractor to trailers,
- adding second/third/fourth trailers in chain,
-
handling cases where the "first" selected prefab is itself a trailer, etc. Each overload iterates m_PrefabChunks and inspects CarTrailerData, CarTractorData, WorkVehicleData, ObjectData and uses m_RequirementData.CheckRequirements to filter. When a valid combination is found they either recursively continue to extend the chain or call PickVehicle to select the final combination.
-
private CheckTractors(...) [multiple overloads]
Several overloads iterate tractor prefabs (CarTractorData) to find tractors compatible with a trailer type (matching TrailerType and fixed-pairing constraints). They mirror the logic of CheckTrailers but for tractors and their candidate tractor-trailer chains. They call PickVehicle to probabilistically select combinations or continue to deeper levels to find multiple-unit layouts. -
private bool PickVehicle(ref Random random, int probability, ref int totalProbability)
Random selection helper. Implements an incremental selection algorithm: totalProbability is incremented by the candidate's probability; the method returns true if random.NextInt(totalProbability) < probability. This is similar to reservoir sampling / incremental weighted random choice with equal "probability" weight passed for each candidate (most callers pass 100). The effect is that each matching candidate has equal chance to become the picked one while scanning through many candidates without storing them all.
Usage Example
// Example usage inside a SystemBase (simplified)
private WorkVehicleSelectData m_SelectData;
private EntityQuery m_PrefabQuery;
private CityConfigurationSystem m_CityConfig; // assumed dependency
protected override void OnCreate()
{
base.OnCreate();
// Create an EntityQuery using the descriptor
var desc = WorkVehicleSelectData.GetEntityQueryDesc();
m_PrefabQuery = GetEntityQuery(desc);
// Initialize the selector
m_SelectData = new WorkVehicleSelectData(this);
// acquire CityConfigurationSystem reference as needed
m_CityConfig = World.GetOrCreateSystem<CityConfigurationSystem>();
}
protected override void OnUpdate()
{
// 1) Prepare chunk list asynchronously
JobHandle chunksHandle;
m_SelectData.PreUpdate(this, m_CityConfig, m_PrefabQuery, Allocator.TempJob, out chunksHandle);
// 2) Ensure async collection is finished before iterating m_PrefabChunks
chunksHandle.Complete();
// 3) Use CreateVehicle to pick and instantiate a vehicle
float workAmount = 100f;
var rnd = new Unity.Mathematics.Random((uint)UnityEngine.Random.Range(1, int.MaxValue));
EntityCommandBuffer.ParallelWriter ecb = /* acquire from a system or pass in */;
Entity created = m_SelectData.CreateVehicle(
ecb,
jobIndex: 0,
ref rnd,
roadTypes: RoadTypes.Car,
sizeClass: SizeClass.Undefined,
workType: VehicleWorkType.Garbage,
mapFeature: MapFeature.None,
resource: Resource.NoResource,
ref workAmount,
transform: new Transform { /* set pos/rot/scale */ },
source: Entity.Null,
state: WorkVehicleFlags.None
);
// 4) Dispose internal chunk list
m_SelectData.PostUpdate(chunksHandle);
}
Notes / tips: - Always call PreUpdate before using CreateVehicle and ensure the JobHandle returned by PreUpdate is completed (jobHandle.Complete()) before iterating m_PrefabChunks. After use, call PostUpdate to dispose m_PrefabChunks. - Use Allocator.TempJob for the temporary chunk list when used within a single frame; ensure PostUpdate is called to dispose. - The class relies on VehicleSelectRequirementData to perform additional per-prefab checks (availability, DLC, city configuration). Make sure CityConfigurationSystem passed in PreUpdate is the correct one. - Randomness uses Unity.Mathematics.Random (passed by ref). CreateVehicle will mutate the Random instance (advance state) and writes a PseudoRandomSeed component on created entity. - CreateVehicle may create multiple runtime entities for multi-piece layouts (primary + attached vehicles) and will add LayoutElement/Controller components so spawned units are linked. - This struct is a value type (cheap to copy) but contains a NativeList that must be properly managed (created/disposed) — do not let the NativeList leak.