Game.Events.InitializeSystem
Assembly: Assembly-CSharp
Namespace: Game.Events
Type: class
Base: GameSystemBase
Summary:
Initializes event entities when they are created. This system inspects newly created Event prefabs and configures/expands them into the runtime effects they represent (fires, traffic accidents, weather phenomena, health incidents, destruction, spectator events, water-level changes, crimes, meetings, calendar events, etc.). It creates specialized archetypes for per-object sub-events (ignite, impact, damage, destroy, spectate, criminal, etc.), selects random targets when required (via a job), enqueues trigger actions, and emits entity commands using an EntityCommandBuffer. Useful for modders who want to understand or extend how game events are instantiated and wired into the ECS runtime.
Fields
-
private BurstCompile] struct RandomEventTargetJob : IJob
Implements a job that scans archetype chunks (from m_TargetQuery) and picks a random Entity that matches requested EventTargetType and optionally a TransportType. It uses a NativeValueoutput to return the selected target. This job reads a variety of component type handles (Building, Tree, Road, Edge, Citizen, PrefabRef, etc.) and a ComponentLookup for TransportDepotData to filter/inspect depot prefabs. -
private struct TypeHandle
Container for cached ComponentTypeHandle/EntityTypeHandle/ComponentLookup instances used when accessing chunk data from the main thread or jobs. The __AssignHandles(ref SystemState) method fills these handles from a SystemState and is called during OnCreateForCompiler. -
private SimulationSystem m_SimulationSystem
Reference to the SimulationSystem (used to read frame index, etc.). -
private CitySystem m_CitySystem
Reference to the CitySystem (used to query city-level buffers like CityModifier). -
private IconCommandSystem m_IconCommandSystem
Reference used to create IconCommandBuffer instances for adding/removing notification icons. -
private EntityQuery m_EventQuery
Query for new event entities to initialize (Created + Event). -
private EntityQuery m_InstanceQuery
Query for existing event instances (Event, exclude Deleted) used to count concurrent instances. -
private EntityQuery m_DisasterConfigQuery
Query to read DisasterConfigurationData singleton (used to add destroyed notifications). -
private EntityQuery m_TargetQuery
Query listing possible target entity types (Any of Building, Tree, Road, Citizen, Household) and excluding Destroyed/Deleted/Temp — used by the random target picker. -
private EntityQuery m_EDWSBuildingQuery
Query for buildings that implement Early Disaster Warning System; used to inform those buildings when a disaster with warnings starts. -
private EntityArchetype m_IgniteEventArchetype
Archetype created for Ignite events (Game.Common.Event + Ignite). Used when initializing fires to spawn Ignite entities. -
private EntityArchetype m_ImpactEventArchetype
Archetype for Impact events (Game.Common.Event + Impact). Used for moving entity collisions / vehicle impacts. -
private EntityArchetype m_AccidentSiteEventArchetype
Archetype for AddAccidentSite events. Created for traffic accident sites. -
private EntityArchetype m_HealthEventArchetype
Archetype for AddHealthProblem events (health incidents on citizens). -
private EntityArchetype m_DamageEventArchetype
Archetype for Damage events used by destruction initialization. -
private EntityArchetype m_DestroyEventArchetype
Archetype for Destroy events that remove or mark objects as destroyed in a disaster. -
private EntityArchetype m_SpectateEventArchetype
Archetype for Spectate events (used by spectator events). -
private EntityArchetype m_CriminalEventArchetype
Archetype for AddCriminal events (crime incidents). -
private TriggerSystem m_TriggerSystem
Reference to TriggerSystem used to create trigger action queues (TriggerAction) that notify other systems about event occurrences. -
private EntityCommandBuffer m_CommandBuffer
Transient EntityCommandBuffer used to enqueue entity creations and component changes during initialization. Created lazily by GetCommandBuffer() and played back in OnUpdate. -
private TypeHandle __TypeHandle
Instance of the TypeHandle struct above, holding cached handles for component access.
Properties
- None (no public properties exposed by this system)
Constructors
public InitializeSystem()
Default constructor with [Preserve] attribute. No custom initialization beyond base constructor.
Methods
-
protected override void OnCreate()
Initializes references to other systems (SimulationSystem, CitySystem, IconCommandSystem, TriggerSystem), creates EntityQueries (m_EventQuery, m_InstanceQuery, m_DisasterConfigQuery, m_TargetQuery, m_EDWSBuildingQuery), builds the various event archetypes (ignite, impact, accident site, health, damage, destroy, spectate, criminal), and calls RequireForUpdate(m_EventQuery) so the system only runs when there are newly created events to process. -
protected override void OnUpdate()
Main update loop: obtains entities matching m_EventQuery (newly created events), iterates them and based on attached marker components (Fire, TrafficAccident, WeatherPhenomenon, HealthEvent, Destruction, SpectatorEvent, Crime, WaterLevelChange, CalendarEvent, CoordinatedMeeting) calls the corresponding InitializeX method to set up sub-entities/components. Enqueues TriggerAction(s) into a TriggerSystem action buffer for each event (per-target or generic). Disposes temporary NativeArrays and plays back the EntityCommandBuffer if it was used. -
private int CountInstances(Entity prefab)
Counts how many active event instances (m_InstanceQuery) reference the given prefab (via PrefabRef). Used to enforce EventData.m_ConcurrentLimit so too many simultaneous instances of the same event prefab aren't allowed. Uses component/arc handles via __TypeHandle and must CompleteDependency() before reading chunks. -
private EntityCommandBuffer GetCommandBuffer()
Lazy-creates and returns a temporary EntityCommandBuffer (Allocator.TempJob) stored in m_CommandBuffer for batching created sub-event entities and component changes during initialization. -
private void InitializeFire(Entity eventEntity)
If FireData indicates a random target type, ensures the event has targets (calls AddRandomTarget if needed) and creates Ignite entities (using m_IgniteEventArchetype) for each target with initial intensity from FireData. -
private void InitializeTrafficAccident(Entity eventEntity)
If TrafficAccidentData specifies a random site type, ensures targets exist (AddRandomTarget), then for each target either spawns an Impact (for Moving entities) with randomized velocity/rotation deltas, or creates an AddAccidentSite for Road entities. -
private void InitializeWeatherEvent(Entity eventEntity)
Configures a WeatherPhenomenon: picks phenomenon and hotspot radii (random between min/max), sets start/end frames (taking disaster warning modifiers into account), picks phenomenon and hotspot positions (from targets or random location), initializes lightning timer, populates HotspotFrame buffer, sets EarlyDisasterWarningDuration on EDWS buildings if applicable, and writes back modified component data (including an InterpolatedTransform created from the phenomenon). -
private void InitializeHealthEvent(Entity eventEntity)
If HealthEventData requests random targets, ensures targets exist and for each target (Resident -> citizen conversion if needed) creates AddHealthProblem entities with flags determined by HealthEventType and a transport probability check based on the citizen's health. If m_RequireTracking is false, clears the target buffer after generating health problems. -
private void InitializeDestruction(Entity eventEntity)
If DestructionData requests random targets, ensures targets exist, and for each target creates a Damage and a Destroy entity. Uses IconCommandSystem to add destroyed notifications (IconCommandBuffer) if DisasterConfigurationData specifies a destroyed notification prefab. Also removes existing problem icons before adding fatal problem icons. -
private void InitializeSpectatorEvent(Entity eventEntity)
If SpectatorEventData requires random sites, ensures targets exist (respecting vehicle transport type if the event uses VehicleLaunchData), creates Spectate entities for each site, and sets the preparation and active frames (m_StartFrame and m_EndFrame) based on the SpectatorEventData durations. -
private void InitializeWaterLevelChangeEvent(Entity eventEntity)
Configures WaterLevelChange: picks max intensity randomly, sets direction, computes Start/End frames (durations depend on change type like tsunami), queries water sources and computes m_DangerHeight from sources that match the direction and target type (sea/river), and writes the updated Duration and WaterLevelChange components. -
private void InitializeCrimeEvent(Entity eventEntity)
If CrimeData requests random targets, ensures targets exist, converts Resident targets to their underlying Citizen entity when found, and creates AddCriminal entities with flags (Planning + Robber for Robbery crimes) to start criminal behavior. -
private void InitializeMeetingEvent(Entity eventEntity)
Expands CoordinatedMeeting targets: for each target that is a Household entity adds its HouseholdCitizen members as CoordinatedMeetingAttendee entries; for a direct Citizen target, adds that citizen to the attendee list. Used to build the attendee buffer for coordinated public meetings. -
private void InitializeCalendarEvent(Entity eventEntity)
Sets a CalendarEvent's Duration start frame and end frame based on CalendarEventData duration and the current simulation frame, writes Duration back, and adds a FindingEventParticipants component (via the command buffer) so a separate system will collect participants. -
private float3 FindRandomLocation(ref Unity.Mathematics.Random random)
Returns a random float3 location with xz chosen uniformly inside [-6000, 6000], used as a fallback phenomenon position for weather events when no target position is available. -
private void AddRandomTarget(DynamicBuffer<TargetElement> targets, EventTargetType targetType, TransportType transportType)
Runs the RandomEventTargetJob (IJob) to scan m_TargetQuery chunks and pick a random entity matching the requested EventTargetType and optional TransportType. If a target is found, appends it to the provided targets buffer. Uses InternalCompilerInterface to obtain ComponentTypeHandle/EntityTypeHandle/ComponentLookup references from __TypeHandle. -
private void __AssignQueries(ref SystemState state)
Compiler helper (generated pattern). Minimal implementation in this decompiled source; used by OnCreateForCompiler. -
protected override void OnCreateForCompiler()
Compiler-time setup invoked to call __AssignQueries and __TypeHandle.__AssignHandles to populate handles and query state needed when compiled AOT or by the ECS code-generation/bridging.
Usage Example
[Preserve]
protected override void OnCreate()
{
base.OnCreate();
// Acquire references to other systems used by InitializeSystem
m_SimulationSystem = base.World.GetOrCreateSystemManaged<SimulationSystem>();
m_CitySystem = base.World.GetOrCreateSystemManaged<CitySystem>();
m_IconCommandSystem = base.World.GetOrCreateSystemManaged<IconCommandSystem>();
m_TriggerSystem = base.World.GetOrCreateSystemManaged<TriggerSystem>();
// Create queries used for initialization and target selection
m_EventQuery = GetEntityQuery(ComponentType.ReadOnly<Created>(), ComponentType.ReadOnly<Event>());
m_InstanceQuery = GetEntityQuery(ComponentType.ReadOnly<Event>(), ComponentType.Exclude<Deleted>());
m_DisasterConfigQuery = GetEntityQuery(ComponentType.ReadOnly<DisasterConfigurationData>());
m_TargetQuery = GetEntityQuery(new EntityQueryDesc
{
Any = new ComponentType[]
{
ComponentType.ReadOnly<Building>(),
ComponentType.ReadOnly<Tree>(),
ComponentType.ReadOnly<Road>(),
ComponentType.ReadOnly<Citizen>(),
ComponentType.ReadOnly<Household>()
},
None = new ComponentType[]
{
ComponentType.ReadOnly<Destroyed>(),
ComponentType.ReadOnly<Deleted>(),
ComponentType.ReadOnly<Temp>()
}
});
// Create archetypes for sub-events
m_IgniteEventArchetype = base.EntityManager.CreateArchetype(ComponentType.ReadWrite<Game.Common.Event>(), ComponentType.ReadWrite<Ignite>());
// ... create other archetypes similarly ...
// Only run when new events are created
RequireForUpdate(m_EventQuery);
}
Notes for modders: - AddRandomTarget uses a job to sample across archetype chunks efficiently. If you change m_TargetQuery component set, make sure TypeHandle is updated accordingly. - Many InitializeX methods create new event entities via the EntityCommandBuffer stored in m_CommandBuffer. The ECB is played back at the end of OnUpdate; if you modify logic to use the ECB directly, ensure proper disposal. - Randomness uses RandomSeed.Next().GetRandom(eventEntity.Index) to produce deterministic per-event randomness. - When adding or changing components referenced in __TypeHandle, update __AssignHandles so component type handles are acquired correctly (this pattern is used by ECS codegen / compiled systems).