Chapter 7: Separating data and logic
The introduction presents separating data from logic and keeping code deliberately simple as ways to reduce complexity and make future features easier to add.
After this chapter you will be able to
- Data and logic separation. Explain that the chapter uses separation of data and logic to make code simpler and easier to work with, and that this problem-solving approach is not limited to Unity.
- Deliberately simple code. Justify the chapter’s choice to write less code and avoid extra abstractions, including the claimed benefits for maintenance, performance, and later features.
- GameData as Save State. Explain why saving core gameplay can be as simple as writing GameData to a file, and how the data needed to load the game defines what belongs in GameData.
- Separate Save Load Logic. Justify keeping the logic that writes or receives game data outside GameData, including when the data may come from a local save or a server.
- Binary save format advantages. Justify choosing binary rather than JSON or XML for this game's save data in terms of conversion work, potential errors, file size, and control over storage.
- Binary byte order. Describe binary serialization as writing variable data into a sequence of bytes and explain the corresponding requirement when reading it back.
- Typed binary reading and writing. Describe how the section uses FileStream with BinaryWriter and BinaryReader, including how value types determine the number of bytes written or read.
- Local save and load roles. Describe the two functions in the static GameDataIO class: SaveLocal() writes referenced game data to a file, while LoadLocal() modifies referenced game data.
- Existing data during loading. Explain why LoadLocal() modifies existing game data rather than allocating new game data, and why allocation is kept in one static logic function.
- Local GameData saving. Describe how SaveLocal() saves the game by creating a file and using BinaryWriter to write every variable in GameData to a FileStream.
- Local load and validation. Describe what LoadLocal() does and which checks it currently omits. Explain why the section leaves failed-load behavior undecided.
- Previously allocated GameData reuse. Explain why LoadLocal() receives a reference to previously allocated GameData instead of allocating a replacement on each call.
- Versioned files and loaders. Describe how the section handles a changed save format without accumulating version branches in one loading function.
- Older save fallback. Trace what happens when the current-version save file does not exist, and explain why retaining older files is useful.
- Saved and allocated enemy counts. Explain how loading handles a saved enemy count that differs from the count allocated under the current balance.
- Binary read and write mismatches. Distinguish the symptoms of missing data from those of reading saved data in the wrong order or as the wrong type, and describe how to check the read and write functions.
- Centralized game data debugging. Explain how keeping game data in one place helps locate an incorrect value after a crash, and describe the debugger check suggested in the section.
- Source-specific loading code. Explain why loading from a new source, such as a database, should have its own class rather than be folded into existing loading code.
- Feature-specific code duplication. Justify why duplicating code for different features can be less complex than sharing it, despite the usual maintenance objections.
- Alive enemies on game start. Explain how Board.Show() uses the alive enemy count and indices to show only alive enemy GameObjects when gameplay starts, including the difference between a new game and a continued game.
- Problem-led asset loading choice. Explain why the section recommends identifying the asset-loading problem before choosing a Unity feature.
- Addressables and memory control. Explain why the section considers Addressables' memory allocation problematic for data-oriented design.
- Shared asset access. Explain why an asset manager is a good candidate for a singleton in this game and why simple loading during initialization is sufficient for its current needs.
- Private editor-assigned prefabs. Describe why the asset manager uses private fields marked with [SerializeField] and provides copies through methods rather than exposing prefab fields directly.
- Board asset retrieval. Describe how Board obtains the player and enemy GameObjects through the AssetManager singleton instead of relying on as many public variables assigned in the Unity editor.
- Separate asset managers by source. Explain why assets loaded from different sources should have separate code, and describe how the section applies this to bundles, the resources folder, and addressables.
- Data-Matched Live Update Choices. Explain how to decide whether an asset should be live-updated and choose an approach based on what part of it changes.
- Live Update Testing Limits. Explain why QA testing of live-updated assets is difficult and why a successful test cannot guarantee a safe live release.
- Separation and fault isolation. Explain how keeping game data together and separating logic by data source reduces the code involved in saving, loading, and debugging.
- Binary saves and format versions. Explain why the section favors binary save data and how a version number in the file name accommodates format changes.
- Safe sharing and solution choice. Justify when duplicated code is preferable to shared code, and why a feature choice should begin with the problem it solves.
What it builds on
- Simple DOD Architecture (chapter 4) · The earlier simple DOD architecture.
- The GameData (chapter 4) · The GameData structure used for gameplay.
- The Logic (chapter 4) · Logic as the class that initializes and modifies GameData.
- The Board implementation (chapter 5) · Board as the part that visually shows the game.
- Using data locality to reduce cache misses (chapter 1) · Explains why data locality matters to memory access.
- AllocateGameData() - Allocating all the data for our game (chapter 4) · The game-data allocation function.
- The Balance (chapter 4) · The balance that determines gameplay data.
- Reducing code complexity by separating data and logic (chapter 1) · Separating data and logic in data-oriented design
Section by section
Introduction
The introduction presents separating data from logic and keeping code deliberately simple as ways to reduce complexity and make future features easier to add.
- Data and logic separation: Explain that the chapter uses separation of data and logic to make code simpler and easier to work with, and that this problem-solving approach is not limited to Unity.
Why it matters: This is the principle behind the chapter’s save/load and asset-management examples. - Deliberately simple code: Justify the chapter’s choice to write less code and avoid extra abstractions, including the claimed benefits for maintenance, performance, and later features.
Why it matters: A simple starting point helps prevent later features from becoming disproportionately difficult to add.
Key terms: separating data from logic, DOD, OOP engine, code complexity, design patterns, interfaces, frameworks
7.1 Save/Load
This section explains why GameData should hold the state needed to restore gameplay while save and load logic stays separate from the data itself.
- GameData as Save State: Explain why saving core gameplay can be as simple as writing GameData to a file, and how the data needed to load the game defines what belongs in GameData.
Why it matters: Keeping the gameplay state in one place makes it clear what must be saved and restored. - Separate Save Load Logic: Justify keeping the logic that writes or receives game data outside GameData, including when the data may come from a local save or a server.
Why it matters: Separating data from its I/O logic keeps GameData focused even when the source of a saved game changes.
Key terms: data-oriented design, GameData, core gameplay, Logic, Board
7.1.1 Storing the save data
This section compares ways to store GameData and explains why the game writes and reads its save data as binary bytes.
- Binary save format advantages: Justify choosing binary rather than JSON or XML for this game's save data in terms of conversion work, potential errors, file size, and control over storage.
Why it matters: The choice of save format affects both the cost of saving and the size of the resulting file. - Text format overhead tradeoffs: Explain where JSON and XML save-file overhead comes from and why shortening JSON keys only partly addresses it.
Why it matters: A text file's readable labels and values can impose substantial storage costs. - Binary byte order: Describe binary serialization as writing variable data into a sequence of bytes and explain the corresponding requirement when reading it back.
Why it matters: The reader cannot recover values correctly unless it interprets the byte sequence in the writer's order. - Typed binary reading and writing: Describe how the section uses FileStream with BinaryWriter and BinaryReader, including how value types determine the number of bytes written or read.
Why it matters: Matching the written and read types is necessary to interpret the saved bytes correctly. - Array and vector serialization: Describe how the section writes an array of enemy positions and how it reads a 32-bit floating-point value.
Why it matters: Compound game data has to be broken into the values the binary stream writes and reads. - PlayerPrefs storage limitations: Explain why the section advises against using PlayerPrefs to hold all the game's save data.
Why it matters: A convenient per-key storage option can become awkward for a growing, data-oriented game.
Key terms: GameData, binary, JSON, XML, overhead, readability, serialization, deserialization, stream of bytes, FileStream
7.1.2 The GameDataIO static class
The section introduces GameDataIO for local saving and loading, and explains why loading modifies existing game data instead of allocating new data.
- Local save and load roles: Describe the two functions in the static GameDataIO class: SaveLocal() writes referenced game data to a file, while LoadLocal() modifies referenced game data.
Why it matters: These distinct roles establish what the later save and load implementations must do. - Existing data during loading: Explain why LoadLocal() modifies existing game data rather than allocating new game data, and why allocation is kept in one static logic function.
Why it matters: Reusing the allocated data avoids repeated allocation costs and keeps memory problems easier to trace.
Key terms: GameDataIO, SaveLocal(), LoadLocal(), game data, memory fragmentation, garbage-collect, static logic function
7.1.3 Saving to a local file
This section explains how SaveLocal() writes GameData to a local file.
- Local GameData saving: Describe how SaveLocal() saves the game by creating a file and using BinaryWriter to write every variable in GameData to a FileStream.
Why it matters: This is the section’s basic save-to-file operation.
Key terms: SaveLocal(), BinaryWriter, GameData, FileStream
7.1.4 Loading from a local file
This section describes how LoadLocal() reads saved GameData, why it reuses an existing object, and what validation and compatibility issues remain unresolved.
- Local load and validation: Describe what LoadLocal() does and which checks it currently omits. Explain why the section leaves failed-load behavior undecided.
Why it matters: It distinguishes the load operation from validation and user-facing failure handling that have not been chosen yet. - Previously allocated GameData reuse: Explain why LoadLocal() receives a reference to previously allocated GameData instead of allocating a replacement on each call.
Why it matters: Repeated loads should not create avoidable garbage-collection and fragmentation costs. - Save data compatibility assumption: State the array-size assumption made during loading and describe which GameData changes would require backward compatibility work.
Why it matters: A load that works for today's GameData may not work for saves made before its shape changes.
Key terms: LoadLocal(), file stream, branch checks, GameData, garbage collector, memory fragmentation, enemy position arrays, backward compatibility
7.1.5 Backwards compatibility
The section shows how to keep manually serialized GameData saves loadable when the save format changes, using versioned files and separate loaders.
- Changing binary save layouts: Explain why adding or removing a GameData variable can break loading of an existing save file.
Why it matters: This is why a GameData change needs a save-compatibility decision, not just a code change. - Versioned files and loaders: Describe how the section handles a changed save format without accumulating version branches in one loading function.
Why it matters: Separate versioned files and loaders keep each loading path tied to a single format. - Older save fallback: Trace what happens when the current-version save file does not exist, and explain why retaining older files is useful.
Why it matters: A user with only an older save can still load it, and an older file may provide a recovery option.
Key terms: GameData, serialization, deserialization, binary layout, version number, SaveLocal(), LoadLocal(), LoadLocalVersion1(), gamedata_v1.dat, gamedata_v2.dat
7.1.6 Handling GameData changes caused by Balance
The section explains how to load saved enemy data when a balance change alters array sizes, including a server-loaded array edge case.
- Saved and allocated enemy counts: Explain how loading handles a saved enemy count that differs from the count allocated under the current balance.
Why it matters: It lets saves remain loadable when a balance change increases or decreases enemy capacity. - Balance count and linear reading: Justify passing the balance into loading and reading saved data linearly rather than seeking past unused entries.
Why it matters: These choices make the compatibility-loading code easier to locate, follow, and debug. - Compatibility branch complexity: Explain why handling a changed enemy count adds complexity to loading code.
Why it matters: Compatibility has a maintenance cost even when the added check looks small. - Oversized server-loaded arrays: Describe why an oversized array received from a server may need reallocation during loading.
Why it matters: Discarding excess entries while loading is not enough if the server will later save the oversized array itself.
Key terms: balance, number of enemies saved, allocated array, balance.NumEnemies, gameData.EnemyPosition.Length, Seek(), linear, backward compatibility, branch, server API
7.1.7 Debugging
This section explains how to diagnose binary save/load bugs by checking for mismatched reads and writes and inspecting centralized game data with a debugger.
- Binary read and write mismatches: Distinguish the symptoms of missing data from those of reading saved data in the wrong order or as the wrong type, and describe how to check the read and write functions.
Why it matters: These different symptoms help narrow down a save/load bug quickly. - Centralized game data debugging: Explain how keeping game data in one place helps locate an incorrect value after a crash, and describe the debugger check suggested in the section.
Why it matters: A breakpoint on the relevant game data can reveal a bad loaded value and point you toward the faulty read.
Key terms: end-of-stream exception, binary data, wrong data type, data-oriented design, game data, breakpoint, debugger
7.1.8 Separating loading by source
This section argues for keeping save/load code separate by data source and sharing only small, data-oriented operations so changes to one feature do not endanger others.
- Source-specific loading code: Explain why loading from a new source, such as a database, should have its own class rather than be folded into existing loading code.
Why it matters: Clear source boundaries make wrong-source loading bugs easier to find. - Feature-specific code duplication: Justify why duplicating code for different features can be less complex than sharing it, despite the usual maintenance objections.
Why it matters: Keeping unrelated features independent reduces the risk of breaking working behavior when one feature changes. - Limits on shared operations: State when the section considers code suitable for sharing and what to do when a change applies to only one feature.
Why it matters: A narrow sharing rule preserves reuse without coupling unrelated feature behavior.
Key terms: data source, database, static class, code duplication, shared code, branching, QA, static, DOD paradigm, data in
7.1.9 Continuing gameplay
This subsection explains how Board.Show() displays the appropriate enemies when starting a new game or continuing a saved one.
- Alive enemies on game start: Explain how Board.Show() uses the alive enemy count and indices to show only alive enemy GameObjects when gameplay starts, including the difference between a new game and a continued game.
Why it matters: It lets the board show the saved game's surviving enemies without showing enemies that are not alive.
Key terms: Board.Show(), gameData.AliveEnemyCount, alive enemy indices array, alive enemy GameObjects
7.2 Asset loading
This section compares Unity asset-loading options and argues for choosing one based on the game's needs, including control over memory and CPU use.
- Problem-led asset loading choice: Explain why the section recommends identifying the asset-loading problem before choosing a Unity feature.
Why it matters: It keeps the choice of asset-loading system tied to the game's requirements rather than a feature's reputation. - Resources and bundle tradeoffs: Distinguish the benefits and drawbacks the section attributes to the Resources folder and asset bundles.
Why it matters: These tradeoffs show why neither dynamic-loading option is universally best. - Addressables and memory control: Explain why the section considers Addressables' memory allocation problematic for data-oriented design.
Why it matters: Allocation timing matters to the performance and memory layout that data-oriented design seeks to control. - Asynchronous loading CPU impact: Explain the gameplay-performance risk the section associates with asynchronous Addressables loading.
Why it matters: An asset loader's CPU scheduling can affect the player's immediate experience, not just memory use.
Key terms: DOD, black-box system, asset loading, Resources folder, asset bundles, Addressables, black box, asynchronously, memory fragmentation, asynchronous asset loading
7.2.1 The asset manager
This section explains why the game uses a singleton asset manager to provide editor-assigned assets to different parts of the game.
- Shared asset access: Explain why an asset manager is a good candidate for a singleton in this game and why simple loading during initialization is sufficient for its current needs.
Why it matters: It connects the asset manager’s design to how this game actually uses assets. - Private editor-assigned prefabs: Describe why the asset manager uses private fields marked with [SerializeField] and provides copies through methods rather than exposing prefab fields directly.
Why it matters: It explains how the manager supplies usable assets without exposing its assigned prefab fields. - Asset-specific retrieval methods: Explain why the asset manager has a dedicated method for each piece of data instead of one generic retrieval method.
Why it matters: Clear retrieval methods make it easier to find where an asset comes from when debugging.
Key terms: asset manager, singleton, initialization, [SerializeField], prefabs, instantiate, private, dedicated method, GetMainMenuUI(), GetMenu(var whichMenu)
7.2.2 Using the asset manager
Board retrieves player and enemy GameObjects through AssetManager, reducing editor-assigned references and making asset sources easier to manage.
- Board asset retrieval: Describe how Board obtains the player and enemy GameObjects through the AssetManager singleton instead of relying on as many public variables assigned in the Unity editor.
Why it matters: This is the change that makes the section’s asset-management benefits possible. - Centralized asset access benefits: Explain why retrieving assets through AssetManager helps with editor-reference mistakes, debugging, and changing where an asset comes from.
Why it matters: These benefits explain why routing Board’s asset access through AssetManager is useful beyond simply moving references.
Key terms: Board, AssetManager, asset manager singleton, GameObjects, public variables, Unity editor, distinct entry point, asset source
7.2.3 Multiple asset sources
When assets come from multiple sources, keep each source’s loading code separate so its origin is clear and problems are easier to debug.
- Separate asset managers by source: Explain why assets loaded from different sources should have separate code, and describe how the section applies this to bundles, the resources folder, and addressables.
Why it matters: Separating loaders by source makes asset problems easier to trace.
Key terms: asset sources, bundles, resources folder, addressables, singletons
7.2.4 Other examples
This section matches asset-loading choices to the data being loaded and explains why live updates require particular caution.
- Tool-Time Balance Data Loading: Explain why the balance data generated at tool time is stored in Unity’s resource folder and how it is loaded at runtime.
Why it matters: The origin and timing of an asset help determine a suitable loading source. - Shared and Zone Asset Bundles: Describe how an open-world game can divide common assets and zone-specific assets into bundles and load them as needed.
Why it matters: Grouping assets by what remains shared and what changes lets the game manage loaded assets as the player moves. - Data-Matched Live Update Choices: Explain how to decide whether an asset should be live-updated and choose an approach based on what part of it changes.
Why it matters: Choosing a source for the data that actually changes avoids unnecessary live-update complexity. - Live Update Testing Limits: Explain why QA testing of live-updated assets is difficult and why a successful test cannot guarantee a safe live release.
Why it matters: A tested update can still fail for real users when delivery conditions or existing asset versions differ.
Key terms: balance data, tool time, resource folder, runtime, asset bundles, shared common bundle, zone bundle, live-update, Addressables, content delivery network (CDN)
7.3 Conclusion
The conclusion shows how separating data, logic, and data sources keeps save/load and asset code easier to understand, change, and debug.
- Separation and fault isolation: Explain how keeping game data together and separating logic by data source reduces the code involved in saving, loading, and debugging.
Why it matters: Clear boundaries narrow down which code you need to inspect when something goes wrong. - Binary saves and format versions: Explain why the section favors binary save data and how a version number in the file name accommodates format changes.
Why it matters: These choices keep saved data compact and format changes from turning loading into a tangle of version branches. - Safe sharing and solution choice: Justify when duplicated code is preferable to shared code, and why a feature choice should begin with the problem it solves.
Why it matters: Restrained sharing and problem-first choices reduce the chance that a small change affects unrelated systems.
Key terms: game data, save state, asset data, logic, binary, JSON, XML, version number, LoadLocalVersion1(), LoadLocal()
7.4 Summary
The chapter summary connects the game’s data layout to save/load decisions and matches asset-loading approaches to the needs of the game.
Where this is used later
- Introducing the meta data (chapter 8) · The earlier static class for game-data input and output.
- The main menu implementation (chapter 8) · Keeping older save files loadable when saved GameData changes.
- Summary (chapter 9) · backward compatibility for saved game data, which the section distinguishes from balance versioning
- Backwards compatibility (chapter 10) · Revisits backwards compatibility
- (chapter intro) (chapter 11) · Introduces the later chapter's discussion of branching and code complexity.
- (chapter intro) (chapter 8) · The earlier separation of code by source is the comparison made for solving distinct problems separately.
- Setting the pool size (chapter 10) · continuing gameplay from saved data
- Summary (chapter 8) · The earlier separation of asset loading from the code that uses assets.
Concepts explained in this chapter
- asset bundleA Unity asset package that stores assets for loading at runtime independently of the main application build.
- BinaryWriterBinaryWriter is a .NET class that writes primitive types as binary data to a stream.
- code duplicationThe practice of implementing the same or similar code in multiple places instead of sharing one implementation.
- binary formatA format that represents data as encoded bytes rather than human-readable text.
- serializationSerialization is the encoding of in-memory data into a storable or transferable representation.
- backward compatibilityBackward compatibility is the ability of newer software or data formats to continue working with older versions or previously created data.
- live asset updateChanging or replacing application content without requiring a new application build.
- data-oriented programmingAn approach to structuring software around the flow and transformation of data rather than relationships between objects.
- UnityA game engine and development platform for creating and running interactive real-time experiences.
- complexity metricA measure of the structural intricacy and difficulty of understanding, modifying, or executing software code.
- Singleton patternA singleton is a pattern that restricts a class to one shared instance and provides centralized access to it.
- Resources folderA Unity project folder whose assets can be loaded at runtime through Unity's Resources asset-loading system.
- BinaryReaderBinaryReader is a .NET class that reads primitive types in binary from a stream.
- ShortA fixed-width integer data type for representing relatively small whole-number values.
- branchControl flow that selects among different execution paths, commonly according to conditions.
- memory allocationThe reservation of memory space for storing program data during execution.
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.
