Skip to content

Game.Buildings.BatteryInitializeSystem

Assembly: Assembly-CSharp.dll
Namespace: Game.Buildings

Type: class

Base: GameSystemBase

Summary:
BatteryInitializeSystem initializes newly added or updated Battery components. It schedules a parallel IJobChunk (InitializeBatteryJob) that: - Reads the entity's PrefabRef and any installed upgrades, - Looks up BatteryData for the base prefab and any installed upgrade prefabs, - Increases the Battery.m_StoredEnergy using ElectricityParameterData.m_InitialBatteryCharge multiplied by the battery capacity (capacityTicks) from BatteryData, - Adds an "empty battery" notification icon (via IconCommandSystem) for batteries whose stored energy remains zero. The system requires an ElectricityParameterData singleton and a query that matches entities with a Battery and a PrefabRef and either Created or Updated (excluding Temp and ServiceUpgrade).


Fields

  • private IconCommandSystem m_IconCommandSystem
    {{ Holds a reference to the IconCommandSystem used to create IconCommandBuffer instances to enqueue notification icons (e.g., battery empty notifications). }}

  • private EntityQuery m_Additions
    {{ Query selecting entities to process. It matches entities that have Battery (read/write) and PrefabRef (read-only), that also have either Created or Updated, and excludes Temp and ServiceUpgrade. This is the primary query scheduled by the system. }}

  • private EntityQuery m_SettingsQuery
    {{ Query used to fetch the ElectricityParameterData singleton (read-only), which provides parameters such as m_InitialBatteryCharge and m_BatteryEmptyNotificationPrefab. }}

  • private TypeHandle __TypeHandle
    {{ Internal struct instance used to cache Entity/Component/Buffer type handles and ComponentLookup instances for use when creating job data (improves performance by avoiding repeated handle lookups). }}

Note: The system also defines nested types (not fields) used by the job: - InitializeBatteryJob (private nested Burst-compiled IJobChunk) — does the per-chunk work described in the summary. - TypeHandle (private nested struct) — holds type and lookup handles and exposes __AssignHandles to fetch them from SystemState.


Properties

  • This type does not expose public properties.
    {{ All relevant data access is performed via fields, nested type handles, and the job struct — there are no public properties on this system to configure at runtime. }}

Constructors

  • public BatteryInitializeSystem()
    {{ Default constructor. It is marked with [Preserve] in the source to prevent stripping. Initialization logic is performed in OnCreate rather than the constructor. }}

Methods

  • protected override void OnCreate()
    {{ Creates/get-or-creates the IconCommandSystem instance, constructs the m_Additions and m_SettingsQuery EntityQueries, and calls RequireForUpdate on both queries so the system only runs when there are relevant entities and settings. The query constructed:

    • All: Battery (RW), PrefabRef (RO)
    • Any: Created (RO), Updated (RO)
    • None: Temp (RO), ServiceUpgrade (RO) This method also ensures type handles will be assigned later (OnCreateForCompiler). }}
  • protected override void OnUpdate()
    {{ Prepares InitializeBatteryJob with the necessary type handles and ComponentLookup references (via InternalCompilerInterface/Get... helpers), creates an IconCommandBuffer from IconCommandSystem, retrieves the ElectricityParameterData singleton, schedules the job in parallel with JobChunkExtensions.ScheduleParallel, and registers the command buffer writer with IconCommandSystem. The job is scheduled on m_Additions and the system's base.Dependency is updated accordingly. }}

  • protected override void OnCreateForCompiler()
    {{ Internal helper used at build/compilation time to call __AssignQueries and __AssignHandles so type handles and queries are set up correctly for compiled code paths. }}

  • private void __AssignQueries(ref SystemState state)
    {{ Small helper used by the compiler-generated flow; in the source it creates and immediately disposes an EntityQueryBuilder — the actual query setup happens in OnCreate. }}

  • Nested: InitializeBatteryJob.Execute(in ArchetypeChunk chunk, int unfilteredChunkIndex, bool useEnabledMask, in v128 chunkEnabledMask)
    {{ Core job logic:

    • Retrieves native arrays/accessors for Entity, PrefabRef, Battery and InstalledUpgrade buffers from the chunk.
    • Detects whether the Created component exists on the chunk (chunk.Has(Created)).
    • For each entity in the chunk:
    • If the chunk indicates Created, calls ProcessAddition for the entity's base prefab.
    • Iterates InstalledUpgrade buffer (if any) and for each installed upgrade:
      • Checks m_CreatedData.HasComponent(item.m_Upgrade) to ensure the upgrade prefab entity has been created.
      • Attempts to get PrefabRef for the upgrade (m_Prefabs.TryGetComponent) and, if present, calls ProcessAddition for the upgrade prefab.
    • If the battery's m_StoredEnergy remains zero after processing, enqueues an empty-battery icon via m_IconCommandBuffer.Add(entity, m_ElectricityParameterData.m_BatteryEmptyNotificationPrefab, IconPriority.Problem).
    • ProcessAddition(prefab, ref Battery): if BatteryData exists for the prefab, adds (long)(m_ElectricityParameterData.m_InitialBatteryCharge * (float)componentData.capacityTicks) to battery.m_StoredEnergy.
    • The job uses ComponentLookup.TryGetComponent / TryGetComponent style calls to fetch BatteryData and PrefabRef where available.
    • The job is Burst-compiled for performance and scheduled in parallel. }}
  • Other job plumbing: explicit IJobChunk.Execute call forwarding to the strongly-typed Execute method (to satisfy the IJobChunk interface).


Usage Example

[Preserve]
protected override void OnCreate()
{
    base.OnCreate();
    m_IconCommandSystem = base.World.GetOrCreateSystemManaged<IconCommandSystem>();
    m_Additions = GetEntityQuery(new EntityQueryDesc
    {
        All = new ComponentType[2]
        {
            ComponentType.ReadWrite<Battery>(),
            ComponentType.ReadOnly<PrefabRef>()
        },
        Any = new ComponentType[2]
        {
            ComponentType.ReadOnly<Created>(),
            ComponentType.ReadOnly<Updated>()
        },
        None = new ComponentType[2]
        {
            ComponentType.ReadOnly<Temp>(),
            ComponentType.ReadOnly<ServiceUpgrade>()
        }
    });
    m_SettingsQuery = GetEntityQuery(ComponentType.ReadOnly<ElectricityParameterData>());
    RequireForUpdate(m_Additions);
    RequireForUpdate(m_SettingsQuery);
}

[Preserve]
protected override void OnUpdate()
{
    var jobData = new InitializeBatteryJob {
        m_EntityType = InternalCompilerInterface.GetEntityTypeHandle(ref __TypeHandle.__Unity_Entities_Entity_TypeHandle, ref base.CheckedStateRef),
        m_PrefabRefType = InternalCompilerInterface.GetComponentTypeHandle(ref __TypeHandle.__Game_Prefabs_PrefabRef_RO_ComponentTypeHandle, ref base.CheckedStateRef),
        m_BatteryType = InternalCompilerInterface.GetComponentTypeHandle(ref __TypeHandle.__Game_Buildings_Battery_RW_ComponentTypeHandle, ref base.CheckedStateRef),
        m_InstalledUpgradeType = InternalCompilerInterface.GetBufferTypeHandle(ref __TypeHandle.__Game_Buildings_InstalledUpgrade_RO_BufferTypeHandle, ref base.CheckedStateRef),
        m_CreatedType = InternalCompilerInterface.GetComponentTypeHandle(ref __TypeHandle.__Game_Common_Created_RO_ComponentTypeHandle, ref base.CheckedStateRef),
        m_Prefabs = InternalCompilerInterface.GetComponentLookup(ref __TypeHandle.__Game_Prefabs_PrefabRef_RO_ComponentLookup, ref base.CheckedStateRef),
        m_BatteryDatas = InternalCompilerInterface.GetComponentLookup(ref __TypeHandle.__Game_Prefabs_BatteryData_RO_ComponentLookup, ref base.CheckedStateRef),
        m_CreatedData = InternalCompilerInterface.GetComponentLookup(ref __TypeHandle.__Game_Common_Created_RO_ComponentLookup, ref base.CheckedStateRef),
        m_IconCommandBuffer = m_IconCommandSystem.CreateCommandBuffer(),
        m_ElectricityParameterData = m_SettingsQuery.GetSingleton<ElectricityParameterData>()
    };

    base.Dependency = JobChunkExtensions.ScheduleParallel(jobData, m_Additions, base.Dependency);
    m_IconCommandSystem.AddCommandBufferWriter(base.Dependency);
}

Notes and tips: - The system relies on BatteryData.capacityTicks and ElectricityParameterData.m_InitialBatteryCharge to compute initial stored energy. Modifying those prefabs/parameters affects how much energy a battery starts with. - Because installed upgrades can modify capacity, the system checks installed upgrade prefabs and applies their BatteryData capacity too. - The IconCommandSystem is used to display a battery-empty notification if no initial energy is assigned. - The job is Burst-compiled and scheduled in parallel; ensure any changes preserve thread-safety and Burst compatibility.