Game.Achievements.AchievementTriggerSystem
Assembly: Assembly-CSharp
Namespace: Game.Achievements
Type: class
Base: GameSystemBase, IDefaultSerializable, ISerializable
Summary: AchievementTriggerSystem monitors game state and entity queries to detect and report achievement progress and unlocks. It integrates with PlatformManager to indicate incremental or absolute progress, to unlock achievements, and to persist some progress in platform user data. The system uses many EntityQueries to inspect created/locked/unlocked objects, production, policies, tourism, population statistics, and custom prefab filters to evaluate dozens of in-game achievements (e.g., ShipIt, HowMuchIsTheFish, AllSmiles, OneofEverything). It also maintains counters and queues used by other systems/jobs to report resource transport and production.
Fields
-
private static ILog sLog
This logger is used to report exceptions or errors related to platform/user-data operations (e.g., while reading/writing user-data for achievement progress). -
private ToolSystem m_ToolSystem
Reference to the ToolSystem grabbed from the world for infoview events and editor checks. -
private CitySystem m_CitySystem
Reference to CitySystem to access city-level components (loan, population, tourism, etc.). -
private CityStatisticsSystem m_CityStatisticsSystem
Used to get city statistics such as tourist count and education counts. -
private CityConfigurationSystem m_CityConfigurationSystem
Used at load time to check mod/unlimited/unlock flags that disable achievements. -
private SimulationSystem m_SimulationSystem
Used to read the current frame index for rate-limited checks. -
private ClimateSystem m_ClimateSystem
Used to check climate/prefab seasons for the FourSeasons achievement. -
private TimeSystem m_TimeSystem
Used for time/season calculations when evaluating FourSeasons. -
private PrefabSystem m_PrefabSystem
Used to fetch prefab data (e.g., ClimatePrefab, AchievementFilterData). -
private EntityQuery m_CreatedObjectQuery
(and many other EntityQuery fields) — the system defines many entity queries used to inspect created objects, parks, service/unique buildings, policies, energy producers, transport lines, plants, aggregate elements, infoviews, etc. These queries are the primary way the system samples the game ECS world to evaluate achievement conditions. -
public NativeCounter m_PatientsTreatedCounter
Counter incremented by other systems when patients are treated; used to update the ALittleBitOfTLC achievement progress. -
public NativeCounter m_ProducedFishCounter
Counter for produced fish used to update the HowMuchIsTheFish achievement. -
public NativeCounter m_OffshoreOilProduceCounter
Counter for offshore oil production used to update ADifferentPlatformer progress. -
private JobHandle m_TransportWriteDeps
Combined write-job dependencies for transport reporting; used to ensure transport queue is processed only after relevant jobs finish. -
private NativeQueue<TransportedResource> m_TransportedResourceQueue
Queue filled by other systems/jobs containing transported resources, consumed by this system when checking the ShipIt achievement. -
private int m_CachedPatientsTreatedCount
Cached value to compute incremental progress since last check. -
private int m_CachedPopulationCount
Cached population milestone used to indicate SixFigures progress increments. -
private int m_CachedHappiness
Cached average happiness used to detect happiness thresholds (AllSmiles / ThisIsNotMyHappyPlace). -
private int m_CachedAttractiveness
Cached attractiveness used to detect SimplyIrresistible. -
private int m_CachedTouristCount
Cached tourist count truncated to thousands for WelcomeOneandAll progress. -
private bool m_CheckUnlocks
Flag to force checking unlock-related achievements on load or when unlock list changes. -
private uint m_LastCheckFrameIndex
Frame-index of last achievement check to limit some checks. -
private HashSet<InfoviewPrefab> m_ViewedInfoviews
Tracks which infoviews the player has viewed (TheInspector achievement). -
private Dictionary<AchievementId, int> m_IncrementalObjectAchievementProgress
Temporary accumulator for incremental object-based achievements gathered each frame. -
private List<AchievementId> m_AbsoluteObjectAchievements
Temporary list of achievements tracked as absolute counters that need to be computed and indicated. -
public ProgressBuffer m_LittleBitOfTLCBuffer
ProgressBuffer instance used to report ALittleBitofTLC achievement progress. -
public ProgressBuffer m_HowMuchIsTheFishBuffer
ProgressBuffer for HowMuchIsTheFish achievement. -
public ProgressBuffer m_ADifferentPlatformerBuffer
ProgressBuffer for ADifferentPlatformer achievement. -
public UserDataProgressBuffer m_SquasherDownerBuffer
Persistent UserDataProgressBuffer for SquasherDowner; syncs with platform user-data and stores progress. -
public UserDataProgressBuffer m_ShipItBuffer
Persistent UserDataProgressBuffer for ShipIt; aggregates transported resource amounts and stores to platform user-data. -
private TypeHandle __TypeHandle
Internal struct that stores Component/Buffer lookups used in multi-thread-aware access; assigned on creation for efficient access.
Properties
- None (the class exposes behavior via public methods rather than C# properties)
Constructors
public AchievementTriggerSystem()
Default constructor. The system's heavy initialization occurs in OnCreate; constructor is present and preserved for the runtime/compiler.
Methods
-
public NativeQueue<TransportedResource> GetTransportedResourceQueue()
Returns the internal transport queue so other systems/jobs can enqueue transported resource events. -
public void AddWriter(JobHandle writer)
Combine job dependencies so this system knows when scheduled writers to the transport queue are complete; used to ensure data safety before processing the queue. -
public bool GetDebugData(AchievementId achievement, out string data)
Returns debugging strings for a handful of achievements (e.g., progress counters of specific progress buffers, and OneofEverything counts). Useful for debugging/in-dev UI. -
[Preserve] protected override void OnCreate()
Primary initialization: creates ProgressBuffer and UserDataProgressBuffer instances; instantiates NativeCounters and NativeQueue; sets cached values; obtains references to other systems; constructs all EntityQueries; hooks infoview changed events. This method sets up the system to monitor game state and persist/load necessary progress. -
[Preserve] protected override void OnUpdate()
Called each tick: checks that achievements are enabled and the game is in a suitable state, then calls CheckInGameAchievements to evaluate conditions and report progress/unlocks. -
private void CheckInGameAchievements()
Core evaluation routine. Processes created objects (object-based achievements), counts parks, checks unlocks, loans, population milestones, transport lines, happiness/attractiveness thresholds, unique service buildings, tourist/education statistics, service district usage, energy mix (zero-emission), industrial diversity (StrengthThroughDiversity), followed citizens (YouLittleStalker), policy achievements, patient/fish/offshore counters, signature buildings, basic city composition (MyFirstCity), plants (ColossalGardener), FourSeasons, lift bridges, ShipIt queue, and updates m_LastCheckFrameIndex. It uses entity queries and component/buffer lookups heavily. -
private void CheckTransportedResources()
Drains the m_TransportedResourceQueue (after ensuring job dependencies are met) and filters transported prefab items using AchievementFilterData buffers to compute progress for the ShipIt achievement; updates m_ShipItBuffer. -
private bool ShouldCheckOffshoreOilProduce()
andprivate bool ShouldCheckProducedFish()
Helpers that test whether production-company related achievements should be evaluated (checks if any produce-resource companies exist and that the corresponding achievement is not already achieved). -
private bool CheckFourSeasons()
Checks the current climate prefab and time progression to determine whether the player has experienced all seasons (FourSeasons achievement). Ensures achievement not already achieved and inspects ClimatePrefab.seasons and temperature ranges. -
private int CalculateEnergyProduction(EntityQuery entityQuery)
Sums m_Capacity from ElectricityProducer components returned by the provided query. Used to compute renewable vs fossil production for ZeroEmission. -
private int CountLiftBridge()
Inspects AggregateElement entities to count non-owned road edges with non-straight geometry crossing waterways (used for DrawMeLikeOneOfYourLiftBridges progress). -
private int CountSignatureBuildings()
Counts unique buildings that are marked with SignatureBuildingData on their prefab; used for MakingAMark and TheArchitect progress. -
private int CountParks()
Counts park prefabs created in the city, applying AchievementFilterData to skip specific prefabs for Groundskeeper if marked. -
private bool CheckOneOfEverything()
Returns whether the city has created every unique service building prefab (accounting for AchievementFilterData exclusions). -
private int CountUniqueServiceBuildingPrefabs()
andprivate int CountUniqueServiceBuildings()
Count prefabs available and created instances respectively, respecting AchievementFilterData filters. -
private bool CheckFilter(DynamicBuffer<AchievementFilterData> datas, AchievementId achievementID, bool defaultResult = false)
Helper that iterates an achievement filter buffer on a prefab and returns whether the prefab is allowed for the specified achievement (defaulting to defaultResult when no filter entry exists). -
private void CheckUnlockingAchievements()
Unlocks RoyalFlush/KeyToTheCity if the player has unlocked all services/buildings respectively. -
private void OnInfoviewChanged(InfoviewPrefab infoview)
Event handler that marks a viewed infoview; unlocks TheInspector when all infoview prefabs are viewed. -
public void Serialize<TWriter>(TWriter writer) where TWriter : IWriter
Writes tracked progress (some ProgressBuffer.m_Progress values) into persistent game save. -
public void Deserialize<TReader>(TReader reader) where TReader : IReader
Reads progress back from save, with conditional compatibility checks against save version and format tags (TLCAchievement and BPDLCAchievement). -
public void SetDefaults(Context context)
Resets runtime caches and sets progress buffers to zero for default/new contexts. -
[Preserve] protected override void OnDestroy()
Disposes NativeCounters, NativeQueue, and UserDataProgressBuffer instances to avoid leaks. -
private void CheckPolicyAchievements()
Counts active policies per district and uses results to unlock ExecutiveDecision and indicate WideVariety progress. -
protected override void OnCreateForCompiler()
andprivate void __AssignQueries(ref SystemState state)
Compiler/runtime helper hooks (internal wiring of queries/handles).
Usage Example
// Example: get the system and interact with its queue, or add a job dependency as an external writer.
var achievementSystem = World.DefaultGameObjectInjectionWorld
.GetOrCreateSystemManaged<Game.Achievements.AchievementTriggerSystem>();
// Get reference to the transport queue to enqueue events from another system/job:
var transportQueue = achievementSystem.GetTransportedResourceQueue();
// When scheduling a job which writes to the transport queue, add its JobHandle so the achievement system
// can wait for completion before processing the queue:
JobHandle writerJobHandle = someJob.Schedule();
achievementSystem.AddWriter(writerJobHandle);
// Typical system initialization is handled by the system itself in OnCreate (preserved):
[Preserve]
protected override void OnCreate()
{
base.OnCreate();
// AchievementTriggerSystem initializes its ProgressBuffers, counters and queries here.
}
Notes: - AchievementTriggerSystem relies on PlatformManager to query and indicate progress/unlocks and on AchievementFilterData buffers on prefabs to include/exclude prefabs from achievement calculations. - Some ProgressBuffer instances persist progress to platform user-data (UserDataProgressBuffer) and can throw/log exceptions if platform user-data APIs fail; sLog is used to report such errors.