Game.BudgetSystem
Assembly: Assembly-CSharp
Namespace: Game.Simulation
Type: class
Base: GameSystemBase, IBudgetSystem
Summary:
BudgetSystem is a game simulation system that collects and caches city economic and budget-related statistics each update. It queries CityStatisticsSystem and ResourceSystem to populate arrays that represent trade volumes and values, household and company wealth, worker counts, tourist data, and overall trade worth. The system allocates persistent NativeArray storage for these aggregates and exposes a set of convenience getters for other systems/mods to read up-to-date summary information. It updates its cached data on OnUpdate and when a game is loaded. It is intended to be long-lived (uses Allocator.Persistent) and must be disposed via OnDestroy which the system implements.
Fields
-
private struct TypeHandle
Internal generated struct used to cache Entity query/handle lookups (here used for BufferLookup). Assigned during OnCreateForCompiler. -
private uint m_LastUpdate
Frame index of the last update. Serves as a simple "HasData" indicator and a timestamp for when the cached values were last refreshed. -
private SimulationSystem m_SimulationSystem
Reference to the SimulationSystem used to obtain the current frameIndex. -
protected NativeArray<int> m_Trade
Per-resource array containing trade volumes for tradable resources. Length equals EconomyUtils.ResourceCount; allocated with Allocator.Persistent. -
protected NativeArray<int> m_TradeWorth
Per-resource trade worth (value), computed from market prices * trade volume. Persistent storage. -
protected NativeArray<int2> m_HouseholdWealth
Single-element array storing household wealth summary (x = total wealth, y = household count). int2 is used to keep sum and count. -
protected NativeArray<int2> m_ServiceWealth
Per-resource array storing service-company wealth and counts (x = total wealth, y = count). -
protected NativeArray<int2> m_ProcessingWealth
Per-resource array storing processing-company wealth and counts. -
protected int m_TotalTradeWorth
Cached sum of all m_TradeWorth entries. -
protected int m_TotalTaxIncome
Reserved/declared field for tax income (not explicitly set in this source; may be used elsewhere). -
private NativeArray<int> m_HouseholdCount
Single-element persistent array storing household count. -
private NativeArray<int> m_ServiceCount
Per-resource persistent array for service company counts. -
private NativeArray<int> m_ProcessingCount
Per-resource persistent array for processing company counts. -
private NativeArray<int2> m_HouseholdWorkers
Single-element array with household worker info (x = employed workers, y = employed + unemployed? used as (workers, max?)). -
private NativeArray<int2> m_ServiceWorkers
Per-resource array storing current and max workers for service companies. -
private NativeArray<int2> m_ProcessingWorkers
Per-resource array storing current and max workers for processing companies. -
private NativeArray<float2> m_CitizenWellbeing
Single-element array storing citizen wellbeing metrics as float2: (average wellbeing, average health) computed from statistics. -
private NativeArray<int> m_TouristCount
Single-element array storing tourist count. -
private NativeArray<int> m_TouristIncome
Single-element array storing tourist income. -
private NativeArray<int2> m_LodgingData
Single-element array storing lodging usage (x = Used, y = Total). -
private CityStatisticsSystem m_CityStatisticsSystem
Reference to CityStatisticsSystem used to read many of the statistics. -
private ResourceSystem m_ResourceSystem
Reference to ResourceSystem used to iterate available resources and resource prefabs. -
private TypeHandle __TypeHandle
Instance of the generated TypeHandle for buffer/query lookups.
Notes: - Most arrays are sized by EconomyUtils.ResourceCount or 1 and are allocated with Allocator.Persistent in OnCreate and disposed in OnDestroy. - Resource indices are resolved using EconomyUtils.GetResourceIndex(resource).
Properties
-
public bool HasData => m_LastUpdate != 0
Returns true once UpdateData has run at least once. Useful to know if cached values are ready. -
public uint LastUpdate => m_LastUpdate
The frame index (from SimulationSystem.frameIndex) of the last UpdateData call. Use to detect staleness.
Constructors
public BudgetSystem()
Default constructor. The class is compiler-generated annotated and relies on OnCreate to initialize its internal state and persistent arrays.
Methods
-
public override int GetUpdateInterval(SystemUpdatePhase phase)
Returns 32768. This dictates the system update scheduling interval (used by the game engine/Systems infrastructure). -
public int GetTotalTradeWorth()
Returns the cached m_TotalTradeWorth — sum of all per-resource trade worth values. -
public int GetHouseholdCount()
Returns household count (from m_HouseholdCount[0]). -
public int GetCompanyCount(bool service, Resource resource)
Returns company count for a given resource. Uses EconomyUtils.GetResourceIndex(resource) to index into either m_ServiceCount or m_ProcessingCount depending on the service flag. -
public int2 GetHouseholdWorkers()
Returns household worker summary int2 from m_HouseholdWorkers[0]. -
public int2 GetCompanyWorkers(bool service, Resource resource)
Returns company worker stats for the given resource from either m_ServiceWorkers or m_ProcessingWorkers. -
public float2 GetCitizenWellbeing()
Returns average citizen wellbeing and health as float2 from m_CitizenWellbeing[0]. -
public int GetTrade(Resource resource)
Returns trade volume for the specified resource from m_Trade. -
public int GetTradeWorth(Resource resource)
Returns trade worth for the specified resource from m_TradeWorth. -
private void SetTradeWorth(Resource resource, ResourceData resourceData)
Helper to compute and store trade worth for a resource: tradeWorth = RoundToInt(marketPrice * tradeVolume). Uses EconomyUtils.GetMarketPrice to get market price. -
public int GetHouseholdWealth()
Returns average household wealth (total wealth / count) if count > 0; otherwise 0. -
public int GetCompanyWealth(bool service, Resource resource)
Returns average company wealth for the specified resource and sector (service vs processing) if count > 0. -
public int GetTouristCount()
Returns tourist count from m_TouristCount[0]. -
public int2 GetLodgingData()
Returns lodging used/total as int2 from m_LodgingData[0]. -
public int GetTouristIncome()
Returns tourist income from m_TouristIncome[0]. -
[Preserve] protected override void OnCreate()
Initializes references to CityStatisticsSystem, SimulationSystem and ResourceSystem. Allocates all NativeArray fields with Allocator.Persistent sized according to EconomyUtils.ResourceCount or 1 as appropriate. -
[Preserve] protected override void OnDestroy()
Disposes all persistent NativeArray allocations and calls base.OnDestroy(). -
[Preserve] protected override void OnUpdate()
Calls UpdateData() each scheduled update. Update scheduling is influenced by GetUpdateInterval. -
protected override void OnGameLoaded(Context serializationContext)
Called when a game is loaded; calls UpdateData() to populate caches immediately after loading. -
private void UpdateData()
Core routine that: - sets m_LastUpdate from SimulationSystem.frameIndex,
- updates BufferLookup handles via __TypeHandle,
- iterates resources and populates m_Trade and m_TradeWorth (for tradable resources),
- reads household, worker, wellbeing, service/processing wealth/workers/counts, tourist and lodging statistics from CityStatisticsSystem,
- calls UpdateTotalTradeWorth() to recalc the total.
This method relies heavily on CityStatisticsSystem.GetStatisticValue(StatisticType, [resourceIndex]) and ResourceSystem prefabs.
-
private void UpdateTotalTradeWorth()
Recomputes m_TotalTradeWorth by summing all elements of m_TradeWorth. -
[MethodImpl(MethodImplOptions.AggressiveInlining)] private void __AssignQueries(ref SystemState state)
Compiler-generated method related to entity query initialization used by the ECS/IL post-compiler. Here it creates and disposes an EntityQueryBuilder; kept for compatibility with the generated system. -
protected override void OnCreateForCompiler()
Called as part of the generated system bootstrap. Calls __AssignQueries and __TypeHandle.__AssignHandles to prepare lookups.
Notes: - Many private/protected members use Unity.Collections.NativeArray and Unity.Mathematics types (int2, float2). - Resource iteration uses ResourceIterator and EconomyUtils helper functions to convert Resource enum -> index and to obtain market price. - The system expects ResourceData components on resource prefabs to determine m_IsTradable and to read market data.
Usage Example
// From another system (GameSystemBase) or mod code with access to a World reference:
protected override void OnSomeMethod()
{
// Get the existing or create-managed BudgetSystem from the same World
var budget = base.World.GetExistingSystemManaged<Game.Simulation.BudgetSystem>()
?? base.World.GetOrCreateSystemManaged<Game.Simulation.BudgetSystem>();
if (budget != null && budget.HasData)
{
int totalTradeWorth = budget.GetTotalTradeWorth();
int householdCount = budget.GetHouseholdCount();
Unity.Mathematics.float2 wellbeing = budget.GetCitizenWellbeing();
int touristIncome = budget.GetTouristIncome();
int lumberTrade = budget.GetTrade(Game.Economy.Resource.Lumber); // example resource
// Use these values for UI, logging or additional calculations
Debug.Log($"TradeWorth: {totalTradeWorth}, Households: {householdCount}, Wellbeing: {wellbeing.x}, TouristIncome: {touristIncome}");
}
}
Notes and tips: - BudgetSystem caches values and only updates them when UpdateData runs. Check HasData/LastUpdate to avoid using stale data. - If you need per-frame immediacy, call UpdateData() only from systems that own BudgetSystem (not recommended to call internal private methods). Prefer to read cached values or request the system run earlier in the update order. - Be mindful of Allocator.Persistent arrays; BudgetSystem disposes them in OnDestroy. Do not attempt to free them yourself.