DEV Community

Cover image for Practical System Design in Game Dev: Controlling Dependencies and Structuring Game Data
Toàn Lương Bảo
Toàn Lương Bảo

Posted on Originally published at toanlb.dev on

Practical System Design in Game Dev: Controlling Dependencies and Structuring Game Data

Practical System Design in Game Dev: Controlling Dependencies and Structuring Game Data

When starting out with Unity on casual games or quick prototypes, most developers experience an initial surge of productivity. Need a feature? Implement it directly in Update(). Need a reference? Type .Instance or drag-and-drop a component in the Inspector. This immediate, convenient approach lets a small game come together in just a few days.

However, that smooth development experience quickly vanishes once we step into larger production projects with dozens of levels, complex progression systems, and multiple interacting mechanics. At this stage, the habit of "designing only as you code" reveals its hidden cost. Scripts begin tangling into a messy web of dependencies: adjusting the player health bar breaks the combat system, adding a skill effect alters the shop currency logic, and whenever state corruption occurs, tracking down which script mutated the variable becomes a debugging challenge.

This topic was sparked by an insightful comment from @Sún Tất under my TikTok post discussing Addressables memory traps during scene changes:

"I have a foundation in Unity, OOP, and basic SOLID, and I've built a few simple casual games on my own. However, when developing larger projects, I struggle to control dependencies between scripts because I usually design as I code. Over time, extending and refactoring features becomes increasingly painful. Where should I start learning game system design to overcome this?

Additionally, how do you organize game data in practice? I often see data split into config data, runtime data, and shared data. How do you actually structure these in production?"

Reading this question brought back vivid memories of my own early career transitions. When moving from small prototypes to production games, we naturally seek answers in textbooks on SOLID, GoF Design Patterns, or Clean Architecture. Yet, most software literature is written for enterprise backends. Translating those rigid abstractions directly into Unity - with its 60 FPS update loops, MonoBehaviour lifecycles, and ScriptableObject asset pipelines - often bloats the project with dozens of empty interfaces, slowing development velocity without resolving the underlying architectural friction.

This post expands upon my response to that discussion, offering a pragmatic architectural blueprint derived from commercial production: from establishing one-way dependency boundaries to organizing four core data categories in game development.


1. The Root Cause of Code Decay: Cyclic Dependencies and Data Role Confusion

Before reaching for complex design patterns, we must identify why game codebases deteriorate over time. In Unity projects, structural decay typically stems from two core mistakes:

Cyclic Dependencies

Without upfront discipline, systems naturally develop two-way dependencies. For instance, PlayerCharacter holds a reference to HealthBarUI to refresh the slider on damage, while HealthBarUI references PlayerCharacter to query maximum health. This mutual dependency results in tight coupling. You cannot reuse PlayerCharacter in a headless simulation or an off-screen mini-game without dragging along UI components, nor can you redesign the HUD without risking regressions in character logic.

Conflating Data Roles

Another common mistake is allowing a single class to hold immutable design constants (base stats), track transient frame-to-frame states (current HP), and handle disk serialization. When static and volatile data mix, resetting gameplay state on restart requires tedious manual resets, and the risk of serializing dirty runtime states into permanent save files increases substantially.


2. Controlling Dependencies: The One-Way Rule and Data-Logic-View

The solution to dependency entanglement does not require memorizing complex patterns; it starts with an architectural boundary: Dependencies must flow in one direction only (One-Way Dependency Rule).

flowchart LR
    subgraph DataLayer["1. Data Layer"]
        D1["Config Data (SO / JSON)"]
        D2["Runtime State (Pure C#)"]
    end

    subgraph LogicLayer["2. Pure Logic Layer"]
        L1["Game Systems (Pure C#)"]
        L2["Combat & Rule Processor"]
    end

    subgraph ViewLayer["3. View Layer"]
        V1["MonoBehaviour View"]
        V2["Particle & Audio Effects"]
    end

    DataLayer -->|"Feeds into Init"| LogicLayer
    ViewLayer -->|"Observes via Events"| LogicLayer

The One-Way Rule Between UI and Gameplay

Establish an uncompromised boundary in your architecture: The UI may know about Gameplay, but Gameplay must never know about the UI.

  • Core Gameplay (damage formulas, health deduction, victory conditions) focuses strictly on domain rules. When player health changes, it broadcasts an event (e.g., event Action<int, int> OnHealthChanged).
  • The UI layer subscribes to this event and updates sliders or triggers animations. Gameplay remains completely oblivious to whether a UI exists, whether it is implemented in Canvas UGUI or UI Toolkit, or whether the game runs headless on a dedicated server.

Decoupling into Three Layers: Data, Logic, and View

To keep code scalable and testable, divide responsibilities across three distinct tiers:

  1. Data (Pure State): Plain C# classes or structs (POCOs) containing raw fields, devoid of heavy business logic.
  2. Logic (Domain Rules): Pure C# classes that process rules, combat calculations, and progression algorithms. These classes do not inherit from MonoBehaviour, avoid UnityEngine.GameObject, and run independently of Unity lifecycle methods. Consequently, game logic can compile and execute in headless NUnit test runners within milliseconds.
  3. View (Presentation & Engine Bridge): Lightweight components inheriting from MonoBehaviour (the Humble View pattern). Their sole duties are forwarding player inputs downward and responding to logic events by triggering animations, sound effects, or particle systems.

The thinner your MonoBehaviour classes are, the fewer lifecycle bugs (Awake, OnDestroy) you encounter, and the easier your systems are to maintain.


3. The Four Data Categories in Production Games

Data is the lifeblood of game architecture. Rather than dumping variables into monolithic manager scripts, organize data into four distinct categories with clear lifecycles and mutation rules. To protect shared data from arbitrary mutation, we apply the Single Writer principle backed by a custom read-only interface named IReadOnlyWallet:

flowchart LR
    subgraph StaticGroup["Immutable Data"]
        C1["Config Data (ScriptableObject / JSON)"]
    end

    subgraph SessionGroup["Session State"]
        R1["Runtime State (Pure C# Class)"]
        S1["Save Data (Dedicated DTO)"]
    end

    subgraph SharedGroup["Shared State"]
        W1["Wallet System (Single Writer)"]
        I1["IReadOnlyWallet Interface"]
    end

    C1 -->|"Initializes base stats"| R1
    R1 -->|"Extracts persistable fields"| S1
    W1 -->|"Exposes read-only contract"| I1

1. Config Data (Static / Immutable)

  • Nature: Pre-authored design constants balanced by designers (enemy base attributes, item catalog prices, progression curves).
  • Storage: ScriptableObject, JSON files, or CSV spreadsheets.
  • Golden Rule: This data is strictly read-only at runtime.
  • Pitfall: Never mutate ScriptableObject fields during gameplay. In the Unity Editor, mutating a ScriptableObject field at runtime permanently writes that value back into the project .asset file on disk, corrupting designer data and producing discrepancies between Editor tests and production builds.

2. Runtime Data (Session State)

  • Nature: Dynamic state of an active match or level (current character HP, remaining ammo, active status buffs).
  • Storage: Pure C# classes instantiated upon entering a level, populated with initial values from Config Data.
  • Golden Rule: When a match ends or restarts, discard the old session state entirely and allocate a fresh instance. Never leave dangling static references to old session objects to prevent memory leak issues.

3. Save Data (Persistent State)

  • Nature: Information that must survive across game application restarts (total accumulated currency, unlocked gear, highest unlocked level).
  • Storage: Serialized to JSON, binary formats, or cloud storage.
  • Golden Rule: Always maintain a dedicated Save DTO (Data Transfer Object). Never serialize raw runtime gameplay objects directly. As a project evolves, runtime classes change frequently to accommodate new mechanics; sharing classes between runtime and storage leads to painful data migration problems for existing players.

4. Shared Data and the Single Writer Principle

  • Nature: Global state accessed across multiple disjoint systems (e.g., a Wallet holding Gold and Gems, queried by the Shop, the HUD header, and Quest reward handlers).
  • The Pitfall: Exposing a public static wallet where any script can execute Wallet.Gold -= 50. As the team expands, race condition bugs and untraceable balance drops inevitably appear.
  • The Solution: The Single Writer Principle.
    • Exactly one system (WalletSystem) owns the authority to mutate balance values via explicit validation methods like TrySpend(int amount) and AddGold(int amount).
    • All external consumers interact exclusively through a read-only interface (IReadOnlyWallet exposing int Gold { get; } and event Action<int, int> OnGoldChanged). External scripts have no mechanism to tamper with balance directly.

4. Bootstrap / Composition Root over Scattered Singletons

A common reaction when sharing game systems is creating dozens of static Singletons: SoundManager, InventoryManager, WalletManager. As explored in our deep dive on Avoiding Singletons in Large Projects, Singletons create hidden dependencies throughout the codebase and render unit testing nearly impossible.

Instead of scattering instantiation across arbitrary Awake() methods, centralize object creation and dependency wiring into a dedicated Bootstrap or Composition Root:

  • A single GameBootstrap.cs script executes in your initial startup scene.
  • It instantiates core services (WalletSystem, SaveSystem) and passes their references into consumer systems via constructors or initialization methods (Init).
  • Practical Tip: Master manual pure dependency injection before adopting heavy DI frameworks such as Zenject or VContainer. Without understanding explicit dependency wiring first, adopting a framework often leads to scattering [Inject] attributes indiscriminately across your project.

5. Code Demonstration: From Tangled Monolith to Decoupled Layers

To illustrate these principles, let us examine a hero combat and wallet system in an action RPG.

In this scenario, a hero possesses maximum health and armor. When taking damage, armor reduces the incoming value before subtracting from health. Concurrently, the player can collect and spend gold. All combat math and wallet rules must be 100% testable via automated unit tests without requiring active Unity scenes or MonoBehaviour lifecycles.

Initial Approach: High Coupling Monolith

Below is the legacy approach: a single MonoBehaviour script managing stats, executing damage calculations, mutating external static singletons, and driving UI components directly.

using System;
using UnityEngine;

public class LegacyHeroController : MonoBehaviour
{
    // Static config and dynamic runtime state mixed together
    public int baseMaxHealth = 100;
    public int armor = 15;
    public int currentHealth;

    // Hard dependency on visual components
    public GameObject damagePopupPrefab;

    private void Awake()
    {
        currentHealth = baseMaxHealth;
    }

    public void TakeDamage(int rawDamage)
    {
        // Business logic mixed into engine component
        int actualDamage = Mathf.Max(1, rawDamage - armor);
        currentHealth -= actualDamage;

        // Direct call to external global singleton
        if (LegacyGameManager.Instance != null && LegacyGameManager.Instance.wallet != null)
        {
            LegacyGameManager.Instance.wallet.gold += 5; // Gold earned upon being hit
        }

        // Direct visual presentation call
        if (damagePopupPrefab != null)
        {
            Debug.Log($"Display popup: -{actualDamage} HP. Current: {currentHealth}");
        }

        if (currentHealth <= 0)
        {
            currentHealth = 0;
            Debug.Log("Hero died!");
        }
    }
}

public class LegacyGameManager : MonoBehaviour
{
    public static LegacyGameManager Instance;
    public LegacyWallet wallet = new LegacyWallet();

    private void Awake()
    {
        if (Instance == null) Instance = this;
    }
}

public class LegacyWallet
{
    public int gold = 100; // Anyone can mutate this arbitrary field
}
Enter fullscreen mode Exit fullscreen mode

Testing whether an attack of 50 damage against 15 armor correctly yields 35 damage requires booting up Unity Play Mode, instantiating LegacyGameManager, and creating scene instances. This coupling breaks test automation.

Refactored Architecture: One-Way Dependencies and Single Writer

We restructure the feature into three clean tiers:

  • HeroConfig: Immutable designer attributes (Config Data).
  • HeroRuntimeState: Active session state (Runtime Data).
  • IReadOnlyWallet and WalletSystem: Shared wallet managed under Single Writer ownership.
  • HeroCombatProcessor: Pure C# domain logic managing damage calculations and events (Pure Logic).
  • HeroHealthView: Lightweight MonoBehaviour observing domain events (Thin View).
using System;
using UnityEngine;

// 1. DATA LAYER: Segregated Config, Runtime State, and Readonly Interface
public class HeroConfig
{
    public int MaxHealth { get; }
    public int Armor { get; }

    public HeroConfig(int maxHealth, int armor)
    {
        MaxHealth = maxHealth;
        Armor = armor;
    }
}

public class HeroRuntimeState
{
    public int CurrentHealth { get; set; }
    public bool IsAlive => CurrentHealth > 0;

    public HeroRuntimeState(int initialHealth)
    {
        CurrentHealth = initialHealth;
    }
}

// Read-only contract for shared state
public interface IReadOnlyWallet
{
    int Gold { get; }
    event Action<int, int> OnGoldChanged; // (newGold, delta)
}

// Single Writer managing currency mutations
public class WalletSystem : IReadOnlyWallet
{
    public int Gold { get; private set; }

    public event Action<int, int> OnGoldChanged;

    public WalletSystem(int startingGold)
    {
        Gold = Math.Max(0, startingGold);
    }

    public void AddGold(int amount)
    {
        if (amount <= 0) return;
        Gold += amount;
        OnGoldChanged?.Invoke(Gold, amount);
    }

    public bool TrySpend(int amount)
    {
        if (amount <= 0 || Gold < amount) return false;
        Gold -= amount;
        OnGoldChanged?.Invoke(Gold, -amount);
        return true;
    }
}

// 2. LOGIC LAYER: Pure C# domain logic independent of UnityEngine
public class HeroCombatProcessor
{
    private readonly HeroConfig _config;
    private readonly HeroRuntimeState _state;

    public event Action<int, int> OnHealthChanged; // (currentHealth, maxHealth)
    public event Action OnHeroDied;

    public HeroCombatProcessor(HeroConfig config, HeroRuntimeState state)
    {
        _config = config ?? throw new ArgumentNullException(nameof(config));
        _state = state ?? throw new ArgumentNullException(nameof(state));
    }

    public int CalculateDamageTaken(int rawDamage)
    {
        if (rawDamage <= 0) return 0;
        int netDamage = rawDamage - _config.Armor;
        return Math.Max(1, netDamage); // Always takes at least 1 damage
    }

    public int TakeDamage(int rawDamage)
    {
        if (!_state.IsAlive) return 0;

        int actualDamage = CalculateDamageTaken(rawDamage);
        _state.CurrentHealth = Math.Max(0, _state.CurrentHealth - actualDamage);

        OnHealthChanged?.Invoke(_state.CurrentHealth, _config.MaxHealth);

        if (!_state.IsAlive)
        {
            OnHeroDied?.Invoke();
        }

        return actualDamage;
    }
}

// 3. VIEW LAYER: Humble MonoBehaviour responding to domain events
public class HeroHealthView : MonoBehaviour
{
    [SerializeField] private string heroName = "Warrior";

    public void Bind(HeroCombatProcessor combatProcessor)
    {
        if (combatProcessor == null) return;
        combatProcessor.OnHealthChanged += HandleHealthChanged;
        combatProcessor.OnHeroDied += HandleHeroDied;
    }

    private void HandleHealthChanged(int currentHp, int maxHp)
    {
        // Visual presentation duties only: update slider, play audio, trigger animation
        Debug.Log($"[View] {heroName} HP: {currentHp}/{maxHp}");
    }

    private void HandleHeroDied()
    {
        Debug.Log($"[View] {heroName} Trigger Death Animation & Sound");
    }
}
Enter fullscreen mode Exit fullscreen mode
flowchart LR
    subgraph SharedDataBlock["Currency System (Single Writer)"]
        WS["WalletSystem (Balance Authority)"]
        IRW["IReadOnlyWallet (Read-Only Interface)"]
    end

    subgraph ConsumerBlock["Consuming Systems"]
        Shop["Shop System (Calls TrySpend)"]
        UIHeader["Header UI (Listens to OnGoldChanged)"]
        Quest["Quest System (Checks Balance Criteria)"]
    end

    WS -->|"Exposes read-only contract"| IRW
    IRW -->|"Safe read access & events"| UIHeader
    IRW -->|"Safe read access & events"| Quest
    Shop -->|"Dispatches purchase request"| WS

Automated Unit Testing (NUnit Runner)

Because Logic and Data are decoupled from MonoBehaviour, all combat rules and currency transactions can be verified instantly with NUnit. Tests execute in CLR memory without engine overhead.

using NUnit.Framework;

[TestFixture]
public class SystemDesignArchitectureTests
{
    [Test]
    public void CalculateDamageTaken_WithArmor_ReducesDamageAccurately()
    {
        // Arrange: Max HP 100, Armor 20
        var config = new HeroConfig(maxHealth: 100, armor: 20);
        var state = new HeroRuntimeState(initialHealth: 100);
        var processor = new HeroCombatProcessor(config, state);

        // Act: 50 raw damage minus 20 armor leaves 30 net damage
        int actualDamage = processor.TakeDamage(50);

        // Assert
        Assert.AreEqual(30, actualDamage);
        Assert.AreEqual(70, state.CurrentHealth);
        Assert.IsTrue(state.IsAlive);
    }

    [Test]
    public void TakeDamage_ExceedingCurrentHealth_ClampsToZeroAndTriggersDeath()
    {
        // Arrange
        var config = new HeroConfig(maxHealth: 100, armor: 10);
        var state = new HeroRuntimeState(initialHealth: 30);
        var processor = new HeroCombatProcessor(config, state);

        bool deathEventFired = false;
        processor.OnHeroDied += () => deathEventFired = true;

        // Act: 60 raw damage -> 50 net damage, exceeding 30 current HP
        processor.TakeDamage(60);

        // Assert
        Assert.AreEqual(0, state.CurrentHealth);
        Assert.IsFalse(state.IsAlive);
        Assert.IsTrue(deathEventFired);
    }

    [Test]
    public void WalletSystem_SingleWriter_PreventsOverspending()
    {
        // Arrange: Starting balance of 100 gold
        var wallet = new WalletSystem(startingGold: 100);

        // Act & Assert 1: Spend 40 gold successfully, leaving balance 60
        bool spendSuccess = wallet.TrySpend(40);
        Assert.IsTrue(spendSuccess);
        Assert.AreEqual(60, wallet.Gold);

        // Act & Assert 2: Spending 70 gold with 60 available fails, preserving balance
        bool overspendSuccess = wallet.TrySpend(70);
        Assert.IsFalse(overspendSuccess);
        Assert.AreEqual(60, wallet.Gold);
    }

    [Test]
    public void WalletSystem_AddGold_FiresEventWithCorrectDelta()
    {
        // Arrange
        var wallet = new WalletSystem(startingGold: 50);
        int capturedNewGold = 0;
        int capturedDelta = 0;

        wallet.OnGoldChanged += (newGold, delta) =>
        {
            capturedNewGold = newGold;
            capturedDelta = delta;
        };

        // Act: Deposit 25 gold
        wallet.AddGold(25);

        // Assert
        Assert.AreEqual(75, capturedNewGold);
        Assert.AreEqual(25, capturedDelta);
        Assert.AreEqual(75, wallet.Gold);
    }
}
Enter fullscreen mode Exit fullscreen mode

6. Using AI as an Architecture Sparring Partner

Large Language Models (LLMs) provide powerful assistance in accelerating architecture design. However, the most effective workflow is not asking AI to "write my entire game", but using it as a sparring partner to critique structural choices before writing code.

A Three-Step Architecture Workflow with AI

  1. Describe Rules and Request a Diagram: Outline system specifications to the model and request a Mermaid diagram (e.g., flowchart LR). Visualizing dependency arrows makes cyclic coupling immediately apparent.
  2. Challenge Choices to Expose Trade-offs: Rather than accepting the first output, query the design:
    • "Why choose an Event over an Interface here?"
    • "If we add multiplayer or an offline simulation mode later, where does this architecture break?"
    • "Does this approach introduce GC allocations in the update loop?"
  3. Lock Architecture Before Code Generation: Only after understanding and accepting the structural trade-offs should you begin coding or prompt the AI to generate scaffolding following your agreed blueprint.

7. Engineering Trade-offs: Choosing the Right Depth

No architecture is universally optimal for every scale. Every structural boundary entails engineering trade-offs:

Approach Benefits Trade-off Cost When to Apply
Ad-hoc Prototyping Maximum initial velocity, zero interface boilerplate, immediate mechanic feedback. Heavy technical debt, hard to maintain beyond 3 months, automated testing impossible. Game jams, rapid prototypes validating core loops in 1 - 2 weeks.
Three-Layer Model (Data - Logic - View) Clean domain logic independent of Unity Engine, 100% automated test coverage in milliseconds. Increases file count, requires upfront wiring and event subscription boilerplate. Core game pillars (Combat, Inventory, Quest, In-game economy).
Single Writer State Management Deterministic data mutation, eliminates race condition bugs, effortless transaction debugging. External modules cannot mutate fields directly; must interact through interfaces and validation methods. Shared critical state: Player Wallet, Progression Level, Character Inventory.
Manual Pure Dependency Injection Transparent dependency flow, zero external library overhead, trivial call stack tracing. Requires manual bootstrapping code, which grows as feature counts expand. Indie projects, mid-sized games (under 15 - 20 interconnected systems).
DI Frameworks (VContainer / Zenject) Automates complex graph resolution, handles scene-based lifetimes and hierarchical scopes cleanly. Steep learning curve, increases build footprint, risk of undisciplined injection abuse. Large titles with multi-disciplinary teams collaborating over several years.

8. Practical Takeaways

System design in game development is not about blindly copying enterprise patterns into Unity; it is the practice of maintaining clear data flow and disciplined dependency direction.

Keep four habits in mind on any new feature:

  1. Diagram dependencies before coding: Ensure arrows flow in one direction only. UI observes Gameplay; Gameplay never depends on UI.
  2. Keep MonoBehaviour thin: Extract calculation logic into pure C# classes. Keep engine components focused strictly on presentation and lifecycle bridging.
  3. Categorize data cleanly: Config Data is immutable; Runtime Data is session-scoped; Save Data has dedicated DTOs; and Shared Data adheres to Single Writer ownership.
  4. Embrace trade-offs: The best architecture serves your team velocity and production scope, not an idealized textbook checklist.

Top comments (0)