Chapter 10: DOD and Dictionaries
The introduction contrasts dictionary lookups with indexed arrays and explains why data-oriented design favors arrays for enemy balance data despite dictionaries’ O(1) complexity.
After this chapter you will be able to
- Dictionary lookup performance. Explain why an O(1) dictionary lookup can be slower than array access in Unity.
- Indexed balance data. Distinguish the dictionary-based OOP example from the array-and-index approach favored here for data-oriented enemy balance data.
- Array versus dictionary lookup. Justify why direct array access can be faster than dictionary lookup even though both are described as O(1), using the section's measurements and cache explanation.
- Enemy ID array indexing. Describe how the game will use enemy type IDs to retrieve balance data without searching or using a dictionary during gameplay.
- Data distinguishing enemy types. Describe the data needed to distinguish the new zombie from the original: velocity, radius, a weight for how often it appears, and a way to select its different-looking GameObject.
- Enemy data and spawn weights. Explain why each enemy type has its own ScriptableObject but its spawn weight is stored separately. Describe the stated purposes of the enemy ID and unique name without explaining their later implementations.
- Enemy prefab name matching. Trace how a designer-assigned enemy prefab is identified for later loading from the AssetManager. Explain why the prefab array’s order and any numeric-looking name prefix do not determine which prefab matches.
- Enemy balance data parsing. Explain that BalanceParser’s parse() function is updated to load all enemy ScriptableObjects and write out their data, using AddObjectsFromDirectory() to find files of that type in a directory and its subfolders.
- Multiple enemy balance data. Explain how Balance represents both the total enemy limit and data for each enemy type, and describe what loading the new balance data does.
- Enemy type IDs and indices. Explain how an enemy type’s ID lets the game reference its data in the balance arrays, and when that ID is assigned.
- Enemy spawn weights. Describe how designers specify which enemy types appear and how often, and how that information enters the balance data.
- Enemy type runtime tracking. Explain why GameData needs an EnemyType array and how its values are used to select enemy data from the balance.
- Weighted spawn type selection. Trace how spawnEnemy() selects an enemy type from balance weights and records it for the spawned enemy.
- Type-specific movement and collisions. Explain how gameplay functions use each stored enemy type to obtain movement velocity and collision radius, including the game-over overlap test.
- Dynamic enemy pool allocation. Explain why the board can no longer instantiate every enemy GameObject at level load, and describe how its pool handles enemies of multiple types without growing its capacity during play.
- Pool capacity and ownership. Explain why MaxEnemyPoolSize is a single Board setting large enough for possible gameplay cases, rather than a value based on enemy weights or placed in Balance.
- Pool metadata and enemy mapping. Describe what the Board’s pool arrays and count track, and how an enemy index maps to a separately indexed GameObject.
- Type matched pool acquisition. Trace how getFreeEnemyPoolIndex() obtains a GameObject and what happens if the pool has no room.
- Showing newly spawned enemies. Trace how the board shows newly spawned enemies: iterate through addedEnemyIndices up to addedEnemyCount, read each enemy’s type, obtain a pool index for that type, and activate the GameObject at that index.
- Hiding removed enemy objects. Explain how the board finds and hides the GameObject for a removed enemy, then marks its pool entry as unused.
- Pool index for enemy movement. Explain that moving an alive enemy requires its pool index so the board can position the correct GameObject.
- Shifting enemy indices. Explain how adding an enemy can make saved enemy IDs refer to the wrong enemy type.
- Stable identifiers and index remapping. Explain how immutable enemy identifiers let a saved game recover the correct enemy types after balance indices change.
- Enemy identifier lookup tables. Explain why backward compatibility needs both an index-to-identifier array and an identifier-to-index dictionary, and how each is used.
- Saved enemy type remapping. Trace how loading a saved enemy type uses its saved unique identifier and the new balance to correct a changed index.
- Enemy type ID swaps. Explain why updating enemy type IDs in sequence can corrupt data when two types swap IDs, and describe how tracking already-updated types prevents a second update.
- Runtime dictionary access. Explain why frequent runtime dictionary access can hurt performance and how tooltime indices let the enemy balance data use arrays instead.
- Bounded object pool lifecycle. Describe how to manage a pool when the enemies to be spawned are unknown, and explain the intended effect on memory fragmentation and garbage collection.
What it builds on
- Using data locality to reduce cache misses (chapter 1) · The value of predictable, local memory access.
- Data locality and contiguous memory - arrays of structs vs arrays of classes (chapter 2) · The data-locality motivation for array-based storage.
- List and dynamic resizing (chapter 6) · Dynamic resizing of a List.
- Moving balance data to an external asset (chapter 9) · The earlier use of a ScriptableObject for balance data.
- The asset manager (chapter 7) · The asset manager used to make assets available to the game.
- Parsing the balance (chapter 9) · The existing balance-parsing process that parse() is updated to extend.
- Using object pools to avoid memory fragmentation and garbage collection (chapter 3) · The earlier approach of pooling GameObjects to avoid repeated allocation and garbage collection.
- Ideal memory allocations (chapter 3) · the preference for establishing memory needs early
Section by section
Introduction
The introduction contrasts dictionary lookups with indexed arrays and explains why data-oriented design favors arrays for enemy balance data despite dictionaries’ O(1) complexity.
- Dictionary lookup performance: Explain why an O(1) dictionary lookup can be slower than array access in Unity.
Why it matters: It helps you judge a data structure by runtime behavior rather than big-O notation alone. - Indexed balance data: Distinguish the dictionary-based OOP example from the array-and-index approach favored here for data-oriented enemy balance data.
Why it matters: This contrast frames why the chapter considers an alternative to dictionary-based enemy lookups.
Key terms: dictionary, hash table, array, O(1), memory access pattern, balance data, key, arrays, index, data-oriented design
10.1 Dictionary performance
This section explains why dictionary lookups can be slower than array access in gameplay code and how integer enemy IDs allow direct balance-array lookups.
- Dictionary growth costs: Explain how adding data can make a dictionary resize and why that can hurt performance.
Why it matters: Lookup speed is not the only cost of choosing a dictionary. - Collisions and linear search: Describe how hashing locates a dictionary bucket and how the next-available-slot approach handles and retrieves colliding keys.
Why it matters: A hash does not always lead straight to the requested value. - Bucket collision chains: Trace how a bucket-linked collision chain stores entries and finds a requested key.
Why it matters: Following a collision chain adds work to a dictionary lookup. - Array versus dictionary lookup: Justify why direct array access can be faster than dictionary lookup even though both are described as O(1), using the section's measurements and cache explanation.
Why it matters: Big-O notation alone does not predict the runtime cost of gameplay lookups. - Enemy ID array indexing: Describe how the game will use enemy type IDs to retrieve balance data without searching or using a dictionary during gameplay.
Why it matters: The game can avoid dictionary lookup overhead when accessing enemy balance data at runtime.
Key terms: dictionary, resized, memory fragmentation, garbage collection, key, hash, bucket, hash collision, entries array, collision chain
10.2 Supporting multiple enemies in the balance
The section identifies the data needed to add a second, bigger, faster, rarer-looking enemy to the game.
- Data distinguishing enemy types: Describe the data needed to distinguish the new zombie from the original: velocity, radius, a weight for how often it appears, and a way to select its different-looking GameObject.
Why it matters: Identifying what differs between enemies gives you the data requirements before you change the game’s implementation.
Key terms: data-oriented design, velocity, radius, weight, GameObject
10.2.1 Storing the new enemy data
This section sets up separate ScriptableObjects for enemy types and explains how their prefab names connect designer-assigned visual data to prefabs available in-game.
- Enemy data and spawn weights: Explain why each enemy type has its own ScriptableObject but its spawn weight is stored separately. Describe the stated purposes of the enemy ID and unique name without explaining their later implementations.
Why it matters: This separation allows enemy spawn rates to change between waves without changing the enemy definitions. - Enemy prefab name matching: Trace how a designer-assigned enemy prefab is identified for later loading from the AssetManager. Explain why the prefab array’s order and any numeric-looking name prefix do not determine which prefab matches.
Why it matters: Matching by a unique full name lets the game find the intended visual prefab without relying on its position in the AssetManager array.
Key terms: ScriptableObject, weight, ID, unique enemy name, balance parsing, prefab, AssetManager, m_enemyPrefabs, [SerializeField], prefab name
10.2.2 Parsing the balance data
This section explains how BalanceParser gathers enemy ScriptableObject data when parsing the balance.
- Enemy balance data parsing: Explain that BalanceParser’s parse() function is updated to load all enemy ScriptableObjects and write out their data, using AddObjectsFromDirectory() to find files of that type in a directory and its subfolders.
Why it matters: This lets the balance parser include enemy data from files throughout the chosen directory tree.
Key terms: BalanceParser, parse(), AddObjectsFromDirectory(), enemy ScriptableObject
10.2.3 Loading the balance data
The section updates Balance for multiple enemy types and states that loading the balance allocates and fills the new per-type data arrays.
- Multiple enemy balance data: Explain how Balance represents both the total enemy limit and data for each enemy type, and describe what loading the new balance data does.
Why it matters: Keeping the overall enemy limit separate from per-type data lets the game support different enemy types.
Key terms: Balance, MaxEnemies, NumEnemyTypes, EnemyVelocity, EnemyRadius
10.2.4 Referencing different enemies
The section explains how enemy types are linked to balance-array data and how spawn weights are supplied for multiple enemy types.
- Enemy type IDs and indices: Explain how an enemy type’s ID lets the game reference its data in the balance arrays, and when that ID is assigned.
Why it matters: The ID connects an enemy type to the right values without hard-coding enemy names into gameplay code. - Enemy spawn weights: Describe how designers specify which enemy types appear and how often, and how that information enters the balance data.
Why it matters: Spawn weights let designers supply the intended mix of enemy types as data. - Ownership of enemy properties: Explain why the earlier single-enemy fields are removed from the balance assets.
Why it matters: Keeping per-enemy properties with each enemy type avoids relying on one shared velocity or radius.
Key terms: enemy type, ID field, EnemySO, balance arrays, AssignIDs(), SpawnData, weights, BalanceSO, tooltime, EnemyVelocity
10.3 Runtime data
The section adds runtime tracking of each enemy’s type so the game can select the corresponding balance data.
- Enemy type runtime tracking: Explain why GameData needs an EnemyType array and how its values are used to select enemy data from the balance.
Why it matters: Tracking an enemy’s type lets the game choose the right balance data for that enemy.
Key terms: EnemyType array, GameData, balance
10.4 The gameplay logic
This section updates gameplay logic to allocate enemy-type data, choose spawn types by balance weights, and use each enemy’s type for movement and collision checks.
- Enemy type array allocation: Describe how AllocateGameData() accommodates multiple enemy types and sizes the enemy arrays.
Why it matters: The game needs a type entry for each enemy its arrays can hold. - Weighted spawn type selection: Trace how spawnEnemy() selects an enemy type from balance weights and records it for the spawned enemy.
Why it matters: Weighted selection controls which types spawn, while the stored type lets later logic identify each enemy. - Type-specific movement and collisions: Explain how gameplay functions use each stored enemy type to obtain movement velocity and collision radius, including the game-over overlap test.
Why it matters: Enemies of different types can move and collide according to their own balance values.
Key terms: EnemyType, AllocateGameData(), balance.MaxEnemies, getRandomEnemyTypeByWeight(), spawnEnemy(), EnemySO, gameData.EnemyType, moveEnemies(), doEnemyToEnemyCollision(), checkGameOver()
10.5 The board
Explains why a pool for randomly spawned enemy types needs a fixed capacity but must allocate individual enemies as needed.
- Dynamic enemy pool allocation: Explain why the board can no longer instantiate every enemy GameObject at level load, and describe how its pool handles enemies of multiple types without growing its capacity during play.
Why it matters: It distinguishes a pool with changing enemy contents from one that repeatedly grows, which the section warns can cause fragmentation and garbage collection.
Key terms: GameObject pool, enemy types, memory fragmentation, garbage collection
10.5.1 Setting the pool size
This section sizes and manages a type-aware GameObject pool so the Board can display enemies whose runtime mix differs from their spawn weights.
- Pool capacity and ownership: Explain why MaxEnemyPoolSize is a single Board setting large enough for possible gameplay cases, rather than a value based on enemy weights or placed in Balance.
Why it matters: A pool sized for the expected spawn ratio could run short of a particular enemy GameObject during play. - Pool metadata and enemy mapping: Describe what the Board’s pool arrays and count track, and how an enemy index maps to a separately indexed GameObject.
Why it matters: The Board can reuse different enemy visuals without assuming an enemy and its GameObject share an index. - Type matched pool acquisition: Trace how getFreeEnemyPoolIndex() obtains a GameObject and what happens if the pool has no room.
Why it matters: Reusing a visual of the correct type avoids creating one whenever an enemy appears. - Board session pool lifecycle: Describe how Show() restores visuals for alive enemies and how Hide() clears the session’s pooled GameObjects.
Why it matters: Loaded enemies get the right visuals, while visuals from an earlier session do not linger in the next one. - Pool indices during Tick: Explain why Tick() uses each enemy’s pool index when updating its visual GameObject.
Why it matters: Using the mapping prevents Tick() from updating the wrong visual when enemy and pool slots differ.
Key terms: MaxEnemyPoolSize, Board, Balance, weights, m_enemyPool, m_enemyPoolType, m_enemyPoolUsed, m_enemyToPoolIndex, m_enemyPoolCount, EnemyType
10.5.2 Showing newly added enemies
This section explains how the board displays newly spawned enemies by selecting a GameObject from the appropriate pool and retaining its pool index for later updates.
- Showing newly spawned enemies: Trace how the board shows newly spawned enemies: iterate through addedEnemyIndices up to addedEnemyCount, read each enemy’s type, obtain a pool index for that type, and activate the GameObject at that index.
Why it matters: The board must select a pooled GameObject for the enemy’s type before it can display that enemy. - Enemy-to-pool index mapping: Explain why the board stores which pool index corresponds to each enemy index after showing a newly added enemy.
Why it matters: Keeping this association lets later board updates reach the right pooled GameObject.
Key terms: addedEnemyIndices, addedEnemyCount, gameData.EnemyType, getFreeEnemyPoolIndex(enemyType), pool index, enemy index
10.5.3 Hiding removed enemies
This subsection explains how to hide a removed enemy’s GameObject when enemy indices must first be mapped to pool indices.
- Hiding removed enemy objects: Explain how the board finds and hides the GameObject for a removed enemy, then marks its pool entry as unused.
Why it matters: The board needs to hide the right object and make its pool entry available again.
Key terms: removedEnemyIndices, pool index, GameObject, active=false, unused
10.5.4 Moving alive enemies
Explains how the board identifies the correct GameObject when moving an alive enemy.
- Pool index for enemy movement: Explain that moving an alive enemy requires its pool index so the board can position the correct GameObject.
Why it matters: Using the pool index lets the board move the GameObject that belongs to the enemy.
Key terms: pool index, GameObject
10.6 Backwards compatibility
The section explains why enemy indices can break saved games when balance files change and compares two ways to preserve backward compatibility.
- Shifting enemy indices: Explain how adding an enemy can make saved enemy IDs refer to the wrong enemy type.
Why it matters: It identifies the save-data failure that the compatibility approaches must prevent. - Numbered filename ordering: Describe how increasing numeric filename prefixes keep newly added enemies from shifting existing indices, and state the drawback for designers.
Why it matters: It shows that a simple way to stabilize indices has a workflow cost. - Stable identifiers and index remapping: Explain how immutable enemy identifiers let a saved game recover the correct enemy types after balance indices change.
Why it matters: Stable identity lets file ordering change without silently changing the enemy types in a saved game.
Key terms: EnemySO, IDs, balance, alphanumeric order, linearly increasing number, file list, unique identifier, game data, index
10.6.1 The Implementation
The section shows how to preserve saved enemy types when their numeric indices change in a new balance, using identifier lookup tables and a dictionary confined to loading.
- Enemy identifier lookup tables: Explain why backward compatibility needs both an index-to-identifier array and an identifier-to-index dictionary, and how each is used.
Why it matters: The two lookup directions let a save retain enemy identity even if balance indices change. - Saved enemy type remapping: Trace how loading a saved enemy type uses its saved unique identifier and the new balance to correct a changed index.
Why it matters: Remapping prevents a saved enemy from becoming a different type merely because its balance index moved. - Loading-only dictionary cost: Justify using a preallocated dictionary here despite the chapter's concern about in-game dictionaries.
Why it matters: Keeping the lookup out of gameplay and sizing it in advance addresses the performance concern raised by using a dictionary.
Key terms: identifier, index, lookup tables, array, dictionary, unique identifier, EnemyNameToID, current balance, gameData.EnemyType, preallocate
10.6.2 Handling edge cases
Explains how swapping enemy type IDs during balance updates can overwrite data and how to prevent it.
- Enemy type ID swaps: Explain why updating enemy type IDs in sequence can corrupt data when two types swap IDs, and describe how tracking already-updated types prevents a second update.
Why it matters: Tracking completed updates keeps a balance change from silently assigning the wrong enemy type.
Key terms: enemy types, new balance, stack-allocated array, garbage collector
10.7 Conclusion
This conclusion explains how to avoid frequent dictionary access during gameplay and how to manage an object pool when its contents cannot be known in advance.
- Runtime dictionary access: Explain why frequent runtime dictionary access can hurt performance and how tooltime indices let the enemy balance data use arrays instead.
Why it matters: Preparing data ahead of time can make access during gameplay more efficient. - Limited dictionary use: Distinguish frequent per-frame dictionary use from the limited use described for backward compatibility.
Why it matters: The practical rule is to control when and how often a dictionary is used, not to ban it. - Bounded object pool lifecycle: Describe how to manage a pool when the enemies to be spawned are unknown, and explain the intended effect on memory fragmentation and garbage collection.
Why it matters: This approach limits the impact of memory fragmentation and the garbage collector.
Key terms: dictionaries, tooltime, indices, balance data, arrays, backward compatibility, runtime, object pools, maximum pool size, unused
10.8 Summary
This summary explains how tool-time indexing, preallocated pools, and load-time mappings keep costly lookups and memory changes out of gameplay.
Where this is used later
- Parallelizing GameObject transform access with TransformAccessArray (chapter 12) · The pooled enemy GameObjects and their existing updates
- Separating data to reduce branch checks (chapter 11) · Assumes the Board has a GameObject pool.
Concepts explained in this chapter
- MapA lookup table is a data structure that maps keys to corresponding values for retrieval.
- hash chainA linked sequence of hash-table entries that share the same bucket because their keys produce colliding hash values.
- hash collisionA hash collision occurs when distinct keys produce the same hash value.
- linear searchA search technique that examines elements sequentially until it finds a match or reaches the end.
- object poolA preallocated collection of slots that holds data or objects for reuse.
- backward compatibilityBackward compatibility is the ability of newer software or data formats to continue working with older versions or previously created data.
- unique identifierA value assigned to an entity to distinguish it from other entities and preserve its identity across changes.
- data-oriented programmingAn approach to structuring software around the flow and transformation of data rather than relationships between objects.
- arrayAn indexed sequence of elements, typically stored in contiguous memory.
- tool timeThe development or preparation phase in which game data is created, processed, or validated before runtime.
- garbage collectionThe automatic process of identifying and reclaiming memory occupied by unreachable objects.
- memory fragmentationMemory fragmentation is the condition in which available memory is divided into separated holes that may not accommodate a requested contiguous allocation.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
