Skip to content

Game.Simulation.GarbageTruckAISystem

Assembly: Assembly-CSharp
Namespace: Game.Simulation

Type: class

Base: GameSystemBase

Summary:
GarbageTruckAISystem implements the AI and behaviour for garbage trucks in the simulation using Unity's Entities (ECS) and Burst jobs. It performs per-vehicle ticking (GarbageTruckTickJob) to manage pathfinding, collection, unloading, parking and dispatch logic; collects side-effects and mutation requests into a thread-safe queue and processes them in GarbageActionJob on the main thread/job that can write component data. The system integrates with pathfinding (PathfindSetupSystem), icon/notification handling (IconCommandSystem), and other simulation subsystems (ServiceFeeSystem, CityStatisticsSystem). It also exposes an update schedule (interval/offset) tuned for the simulation frame timing.


Fields

  • private EndFrameBarrier m_EndFrameBarrier
    Used to create an EntityCommandBuffer for changes that must be applied at the end of the frame. This ensures structural changes from the jobs are deferred and applied safely on the main thread.

  • private PathfindSetupSystem m_PathfindSetupSystem
    Reference to the pathfind setup system used to enqueue and coordinate pathfinding work (the pathfind queue writer used by vehicle jobs).

  • private IconCommandSystem m_IconCommandSystem
    Reference to the icon/notification system; used to add/remove visual notifications (e.g. garbage piling up icons) from the GarbageActionJob.

  • private ServiceFeeSystem m_ServiceFeeSystem
    Reference to the service fee system; used to register job writers/queues that may interact with service fees (system integration for job dependencies).

  • private SimulationSystem m_SimulationSystem
    Reference to the core simulation system; used to read the simulation frame index and produce consistent seeding and timing behavior.

  • private CityStatisticsSystem m_CityStatisticsSystem
    Reference used to register writers that update city statistics (garbage-related stats updates).

  • private EntityQuery m_VehicleQuery
    Query selecting garbage truck vehicle entities (CarCurrentLane, Owner, PrefabRef, PathOwner, GarbageTruck, Target etc.). This is the query used to schedule the parallel IJobChunk (GarbageTruckTickJob).

  • private EntityArchetype m_GarbageCollectionRequestArchetype
    Archetype used to create garbage collection request entities (ServiceRequest + GarbageCollectionRequest + RequestGroup).

  • private EntityArchetype m_HandleRequestArchetype
    Archetype used to create handle-request event entities (HandleRequest + Event) when a vehicle commits to handle a collection request.

  • private ComponentTypeSet m_MovingToParkedCarRemoveTypes
    ComponentTypeSet that lists components to remove when a vehicle transitions from moving to parked — used via EntityCommandBuffer to convert movement/drive components into parked state.

  • private ComponentTypeSet m_MovingToParkedAddTypes
    ComponentTypeSet that lists components to add when a vehicle parks (ParkedCar, Stopped, Updated).

  • private TypeHandle __TypeHandle
    Internal cached set of component/handle type handles used by the jobs (auto-generated helper to resolve ComponentTypeHandles/BufferTypeHandles/ComponentLookups).

  • private EntityQuery __query_647374864_0
    Internal cached EntityQuery for GarbageParameterData (used by jobs to read garbage system parameters).

  • private EntityQuery __query_647374864_1
    Internal cached EntityQuery for BuildingEfficiencyParameterData (used to obtain garbage efficiency penalty and similar parameters).

Properties

  • (no public properties)
    This system does not expose public properties. It primarily works through ECS queries, jobs and internal references to other systems.

Constructors

  • public GarbageTruckAISystem()
    Default constructor. The system is created by the world (GetOrCreateSystemManaged) and setup is completed in OnCreate. There is no custom initialization logic in the ctor; OnCreate does the heavy setup and dependency registration.

Methods

  • public override int GetUpdateInterval(SystemUpdatePhase phase)
    Returns the update interval (16) used to determine how frequently the system runs relative to simulation frames.

  • public override int GetUpdateOffset(SystemUpdatePhase phase)
    Returns the update offset (2) for scheduling the system's update phase.

  • [Preserve] protected override void OnCreate()
    Initializes references to dependent systems (EndFrameBarrier, PathfindSetupSystem, IconCommandSystem, ServiceFeeSystem, SimulationSystem, CityStatisticsSystem), creates entity archetypes for requests/handlers, sets up the vehicle EntityQuery and the ComponentTypeSets used when parking, and registers required singletons (GarbageParameterData, ServiceFeeParameterData, BuildingEfficiencyParameterData). Called once when the system is created.

  • [Preserve] protected override void OnUpdate()
    Main update method. Creates a NativeQueue for queued GarbageAction items and schedules two Burst-compiled jobs:

  • GarbageTruckTickJob (IJobChunk, scheduled parallel over vehicle query): per-vehicle logic (path reset, path selection, request checks, try-collect/unload, parking checks, estimated fullness, pathfinding setup). It enqueues actions into m_ActionQueue and pathfind requests into PathfindSetupSystem queue.
  • GarbageActionJob (IJob): dequeues GarbageAction entries and performs component writes / buffered operations that must be executed after the chunk jobs (collecting garbage amounts, applying unload transfers to facilities' economy buffers, setting flags, adding collection requests to buildings, clearing lane flags on other trucks, bumping dispatch indices, and icon updates). The method wires job dependencies and registers the produced job handles with systems that own the queues/command buffers. It also ensures proper disposing of the NativeQueue and registers command buffer/job producer handles with EndFrameBarrier and other systems.

  • protected override void OnCreateForCompiler()
    Internal helper invoked by generated code/path to assign queries and type handles for compiler-time wiring. Ensures the generated __AssignQueries and __TypeHandle assignment are performed.

  • private void __AssignQueries(ref SystemState state)
    Auto-generated helper that builds and stores the internal EntityQuery objects used to fetch parameter singletons needed by the jobs (GarbageParameterData and BuildingEfficiencyParameterData).

  • Nested types (high level descriptions; they are important parts of the system):

  • private enum GarbageActionType
    Types of actions enqueued by the per-vehicle job for later processing: Collect, Unload, AddRequest, ClearLane, BumpDispatchIndex.
  • private struct GarbageAction
    Represents a queued action with fields for vehicle, target, request, type, capacity and max amount.
  • [BurstCompile] private struct GarbageTruckTickJob : IJobChunk
    The main per-vehicle job running in parallel. Responsible for the bulk of the garbage truck AI: resetting and building paths, detecting and enqueuing collection/unload requests, selecting dispatches, parking, checking/removing waypoints, estimating garbage, and enqueuing Pathfind setup items and GarbageAction items.
  • [BurstCompile] private struct GarbageActionJob : IJob
    Processes GarbageAction queue items on a job that can write component data and call icon/economy updates. Handles the actual mutations: transferring garbage between trucks and producers/facilities, setting producer request data, bumping dispatch indices, setting ClearChecked flags on other trucks, updating efficiencies and icons.
  • private struct TypeHandle
    Auto-generated container for ComponentTypeHandles, BufferTypeHandles and ComponentLookup/BufferLookup instances used by the jobs.

  • Many private helper methods exist within GarbageTruckTickJob (implemented inside the job struct) to manage pathfinding, collection and request logic. Notable behaviours:

  • Path reset and parking behavior (ResetPath, ParkCar).
  • Pathfinding setup (FindNewPath, RequestTargetIfNeeded).
  • Dispatch selection and request pre-processing (SelectNextDispatch, CheckServiceDispatches, PreAddCollectionRequests, BumpDispachIndex).
  • Sidewalk/path adjustments and collection insertion (FindClosestSidewalk, AddPathElement, AddCollectionRequests).
  • Detection of garbage presence on lanes and buildings (CheckGarbagePresence, CheckGarbagePresence overloads).
  • Actual enqueueing of collection/unload/add request/clear lane actions via m_ActionQueue.
  • UnloadGarbage enqueues Unload actions and triggers quantity/effects updates.

Usage Example

// Example: Retrieve the garbage truck AI system from the World and (if needed) inspect it.
// Typical usage in a mod: get the system to query or ensure it's created/initialized.
using Unity.Entities;
using Game.Simulation;

var world = World.DefaultGameObjectInjectionWorld;
var garbageSystem = world.GetOrCreateSystemManaged<GarbageTruckAISystem>();

// The system executes automatically according to its update interval.
// For debug or testing you can force it to update in editor tests by calling:
garbageSystem.Update();
// (Note: calling Update directly is normally not needed and should be done carefully
//  because systems expect to be driven by the game's bootstrap/simulation loop.)

{{ Additional details: - This system is designed to be deterministic and thread-safe: heavy per-vehicle work runs in a parallel IJobChunk and only enqueues lightweight action structs to a NativeQueue; a single job consumes that queue to perform the actual ECS structural writes and buffer updates. - Jobs are Burst-compiled for performance (see [BurstCompile] attributes). - Many behaviours and thresholds (e.g., m_CollectionGarbageLimit, m_RequestGarbageLimit, penalties) are read from the GarbageParameterData and BuildingEfficiencyParameterData singletons — these are required for the system to run and are ensured by RequireForUpdate calls in OnCreate. - For modders: to influence garbage behaviour, consider overriding or modifying GarbageParameterData, adding/removing requests/entities that match the system's archetypes, or interacting with the system via the PathfindSetupSystem / IconCommandSystem where appropriate. }}