Skip to content

Game.Prefabs.GarbageTruckSelectData

Assembly: Assembly-CSharp
Namespace: Game.Prefabs

Type: struct

Base: System.ValueType

Summary:
Utility struct used by city systems to select and spawn garbage truck prefabs. It caches prefab archetype chunks (via an EntityQuery), holds component type/lookup handles and vehicle selection requirement data, and provides methods to pick an appropriate garbage truck prefab based on current garbage capacity and to create instances (both in single-threaded and job-parallel contexts). The struct manages native memory acquired during PreUpdate and must be balanced with a PostUpdate call to dispose that memory.


Fields

  • private NativeList<ArchetypeChunk> m_PrefabChunks
    A NativeList containing the archetype chunks returned by an EntityQuery. Populated in PreUpdate using query.ToArchetypeChunkListAsync. Must be disposed (in PostUpdate) with the JobHandle produced by the async call.

  • private VehicleSelectRequirementData m_RequirementData
    Helper that encapsulates vehicle selection requirements (filters/conditions) and per-chunk requirement state. Used to skip prefabs that don't meet configured requirements.

  • private EntityTypeHandle m_EntityType
    Entity type handle used to read the Entity array from each chunk. Updated in PreUpdate so it's valid for subsequent chunk access.

  • private ComponentTypeHandle<GarbageTruckData> m_GarbageTruckType
    ComponentTypeHandle for reading GarbageTruckData from chunk elements. Updated in PreUpdate.

  • private ComponentLookup<ObjectData> m_ObjectData
    ComponentLookup used to access ObjectData for a prefab Entity (for example to obtain its archetype). Updated in PreUpdate.

  • private ComponentLookup<MovingObjectData> m_MovingObjectData
    ComponentLookup used to access MovingObjectData for a prefab Entity (to obtain stopped/parked archetypes). Updated in PreUpdate.

Properties

  • None (this struct exposes no public properties).

Constructors

  • public GarbageTruckSelectData(SystemBase system)
    Initializes the selection helper with the given SystemBase. Sets up internal VehicleSelectRequirementData and obtains initial type/lookup handles:
  • m_PrefabChunks is initialized to default (empty).
  • m_RequirementData is constructed using the provided system.
  • m_EntityType, m_GarbageTruckType, m_ObjectData, m_MovingObjectData are retrieved from the system (with appropriate isReadOnly flags for the handles/lookups).

Notes: - This constructor does not query or allocate chunk lists. Call PreUpdate before using selection/creation methods.

  • (implicit) parameterless struct constructor
    The default struct constructor exists but leaves fields in default state. You should prefer the constructor above before using the instance.

Methods

  • public static EntityQueryDesc GetEntityQueryDesc()
    Returns an EntityQueryDesc describing the prefabs considered for garbage trucks. The query requires:
  • GarbageTruckData (ReadOnly)
  • CarData (ReadOnly)
  • ObjectData (ReadOnly)
  • PrefabData (ReadOnly) and excludes entities with Locked (ReadOnly). Use this descriptor to create the EntityQuery passed into PreUpdate.

  • public void PreUpdate(SystemBase system, CityConfigurationSystem cityConfigurationSystem, EntityQuery query, Allocator allocator, out JobHandle jobHandle)
    Prepare the selector for use in the current frame:

  • Calls query.ToArchetypeChunkListAsync(allocator, out jobHandle) to populate m_PrefabChunks asynchronously.
  • Updates m_RequirementData (so filters/requirements reflect current city config).
  • Updates all stored type/lookups (m_EntityType, m_GarbageTruckType, m_ObjectData, m_MovingObjectData) so they are valid for current system state. Parameters:
  • system: the SystemBase invoking the update (used to update handles).
  • cityConfigurationSystem: used by m_RequirementData.Update to evaluate requirements.
  • query: EntityQuery built from GetEntityQueryDesc (or compatible).
  • allocator: Allocator to pass to ToArchetypeChunkListAsync.
  • out jobHandle: the JobHandle representing the async chunk-list creation; must be used when disposing the list.

Important: callers must call PostUpdate and pass the JobHandle returned here to ensure the NativeList is disposed correctly.

  • public void PostUpdate(JobHandle jobHandle)
    Disposes m_PrefabChunks using the provided jobHandle to ensure proper synchronization with any async operations started in PreUpdate. Call this after all usages of the prefab list are complete.

  • public Entity SelectVehicle(ref Random random, ref int2 garbageCapacity)
    Selects and returns a prefab Entity for a garbage truck suitable for the current garbageCapacity. This is a convenience wrapper that calls the private GetRandomVehicle. On success, updates the provided garbageCapacity to the selected truck's capacity (so callers can know the truck's capacity that was chosen). Returns Entity.Null if no suitable prefab is found.

  • public Entity CreateVehicle(EntityCommandBuffer commandBuffer, ref Random random, Transform transform, Entity source, Entity prefab, ref int2 garbageCapacity, bool parked)
    Create a garbage truck entity using a non-parallel EntityCommandBuffer:

  • If prefab == Entity.Null, it first selects a prefab with GetRandomVehicle using the provided random and garbageCapacity. If still null, returns Entity.Null.
  • Creates an entity with an archetype determined by GetArchetype(prefab, parked).
  • Sets components on the created entity:
    • Transform (position/rotation/scale)
    • PrefabRef(prefab)
    • PseudoRandomSeed initialized from the provided Random
  • If parked == false, adds TripSource(source) and Unspawned components.
  • Returns the created Entity (or Entity.Null). Usage: call after PreUpdate and before PostUpdate.

  • public Entity CreateVehicle(EntityCommandBuffer.ParallelWriter commandBuffer, int jobIndex, ref Random random, Transform transform, Entity source, Entity prefab, ref int2 garbageCapacity, bool parked)
    Parallel-job-safe overload of CreateVehicle using an EntityCommandBuffer.ParallelWriter and a jobIndex. Behavior is the same as the single-threaded overload but writes commands with the provided jobIndex.

  • private EntityArchetype GetArchetype(Entity prefab, bool parked)
    Returns the EntityArchetype to use when creating the vehicle:

  • If parked is true: returns m_MovingObjectData[prefab].m_StoppedArchetype (the stopped/parked archetype).
  • If parked is false: returns m_ObjectData[prefab].m_Archetype (the regular archetype).

  • private Entity GetRandomVehicle(ref Random random, ref int2 garbageCapacity)
    Core selection algorithm:

  • Iterates over all cached archetype chunks (m_PrefabChunks).
  • For each chunk, retrieves the Entity array and GarbageTruckData array using the stored type handles.
  • Uses m_RequirementData.GetChunk and CheckRequirements to skip prefabs that do not meet requirements.
  • Computes the difference between a prefab's garbage capacity and the provided garbageCapacity and ranks prefabs by this difference. The logic attempts to favor prefabs with capacities closest to the desired capacity but includes a probabilistic selection:
    • num3 and num2 are used to group candidates by capacity-difference; whenever a new closer difference is found, the accumulated probability resets.
    • For each candidate, PickVehicle is called to do a weighted-random pick among candidates at the same priority.
  • If a prefab is chosen, stores its capacity into 'num' and sets the result to that Entity.
  • After iteration, writes the chosen truck's capacity into the garbageCapacity out parameter and returns the chosen Entity or Entity.Null if none matched.

This method relies on m_PrefabChunks and updated type/lookups; ensure PreUpdate has been called and the chunk list is valid.

  • private bool PickVehicle(ref Random random, int probability, ref int totalProbability)
    Utility used by GetRandomVehicle to perform an incremental/weighted selection. It increases totalProbability by the supplied probability and returns true if random.NextInt(totalProbability) < probability. This implements a form of reservoir selection / incremental weighted choice: as candidates are evaluated, each candidate receives a share of the selection probability relative to the accumulated total.

Usage Example

// Example usage inside a SystemBase
public partial class GarbageTruckSpawnSystem : SystemBase
{
    private GarbageTruckSelectData m_SelectData;
    private EntityQuery m_GarbageTruckPrefabQuery;
    private JobHandle m_PreloadHandle;

    protected override void OnCreate()
    {
        base.OnCreate();
        m_SelectData = new GarbageTruckSelectData(this);
        m_GarbageTruckPrefabQuery = GetEntityQuery(GarbageTruckSelectData.GetEntityQueryDesc());
    }

    protected override void OnUpdate()
    {
        // Prepare selection data (async chunk list)
        m_SelectData.PreUpdate(this, /*cityConfigurationSystem*/ default, m_GarbageTruckPrefabQuery, Allocator.TempJob, out m_PreloadHandle);

        // Use selection (single-threaded example)
        var rnd = new Unity.Mathematics.Random(1234);
        Unity.Mathematics.int2 desiredCapacity = new Unity.Mathematics.int2(0, 100);
        Entity chosenPrefab = m_SelectData.SelectVehicle(ref rnd, ref desiredCapacity);
        if (chosenPrefab != Entity.Null)
        {
            var ecb = new EntityCommandBuffer(Allocator.Temp);
            var transform = new Transform { /* ... */ };
            m_SelectData.CreateVehicle(ecb, ref rnd, transform, Entity.Null, chosenPrefab, ref desiredCapacity, parked: false);
            ecb.Playback(EntityManager);
            ecb.Dispose();
        }

        // Dispose the native chunk list (must use the JobHandle from PreUpdate)
        m_SelectData.PostUpdate(m_PreloadHandle);
    }
}

Notes and tips: - Always call PreUpdate before calling SelectVehicle/CreateVehicle so the internal archetype chunk list and component handles are valid. - Always call PostUpdate with the JobHandle returned by PreUpdate to avoid leaking native memory. - If you call the parallel CreateVehicle overload inside a job, ensure you use the ParallelWriter and pass the correct jobIndex. - The selection algorithm considers configured requirements (VehicleSelectRequirementData) — ensure city configuration is supplied and up to date via PreUpdate.