Back to articles
Writing Unity Game Systems: Zero-Allocation Performance Guide
21 September 2026 8 min read

Writing Unity Game Systems: Zero-Allocation Performance Guide

Writing Unity Game Systems: Zero-Allocation Performance Guide

Writing Unity game systems that ship means writing modular, zero-allocation code with data-oriented architecture. You write deterministic RPG mechanics, write RPC-based multiplayer networking, and write technical documentation that scales. The payoff: O(1) lookups, no garbage collection spikes, and systems that integrate in hours, not weeks. This guide covers how to write Unity code that performs, from experience curves to spawners, using production-tested patterns. Whether you're writing an RPG leveling system or writing a networked RTS, the principles are identical: allocate once, reuse forever, and document everything.

Most Unity projects fail performance targets not because of graphics, but because of poorly written gameplay code. Per-frame allocations, MonoBehaviour sprawl, and ad-hoc networking destroy frame budgets. The fix is architectural: write systems with explicit ownership, pooled memory, and deterministic execution. Let's break down how to write each layer correctly.

A professional Unity developer workspace with dual monitors. Left monitor shows C# code in Visual Studio with dark theme and…

Writing Zero-Allocation Unity Code: The Core Rules

How do I write zero-allocation Unity code? You write it by eliminating per-frame heap allocations: no new in Update, no LINQ in hot paths, no string concatenation, no boxing. Use structs, object pools, and cached references. The Unity garbage collector (GC) is incremental but still causes frame spikes when allocations exceed budget. On mobile, a single 1KB allocation per frame at 60 FPS equals 60KB/s, triggering GC every few seconds. Write with that number in mind.

Rule 1: Cache Everything You Can

Write GetComponent calls in Awake or Start, never in Update. Cache transform references, animator hashes, and layer masks. A GetComponent<Transform>() call costs roughly 15-20ns; called 100 times per frame across 50 objects, that's measurable. Write once, store in a field, reuse.

Rule 2: Pool Aggressively

Write object pools for bullets, enemies, UI elements, and audio sources. Instantiate and Destroy are expensive: each Instantiate triggers allocation and Awake/OnEnable; each Destroy triggers GC pressure. A pooled spawner reuses 200 bullets with zero allocations after warmup. This is exactly what Spawner Advanced & Pooling delivers: wave-based spawning with integrated pooling, eliminating GC spikes in FPS, RPG, and RTS games.

💡 Tip

Write a PooledObject struct that stores the prefab ID, pool index, and active state. Use a Dictionary<int, Stack<GameObject>> for O(1) retrieval. Never call Instantiate during gameplay after warmup.

Rule 3: Use Structs and Arrays Over Classes and Lists

Write hot-path data as structs in arrays, not classes in lists. A List<Enemy> of classes scatters memory and causes cache misses. An Enemy[] of structs is contiguous, cache-friendly, and allocation-free. This is data-oriented design in practice. For 10,000 entities, array-of-structs can be 5-10x faster than list-of-classes due to cache locality.

PatternAllocation per FrameGC ImpactUse Case
Instantiate/Destroy~2KB per objectHigh, frequent spikesPrototyping only
Object Pool0 after warmupNoneBullets, enemies, UI
List<Class>Growth allocationsMediumEditor tools
Array of Structs0 (pre-allocated)NoneHot gameplay loops

Writing Modular RPG Systems: Leveling, Skills, and Inventory

Writing RPG mechanics demands modularity. You write experience curves, skill trees, and inventory as independent systems with clean interfaces. Coupling them creates spaghetti. Write each as a self-contained module that communicates through events or interfaces.

How Do I Write an Experience Curve System?

Write experience curves as pure functions: int GetXpForLevel(int level). Avoid hardcoded formulas; use ScriptableObjects or data tables. Write 40+ curve algorithms (linear, exponential, polynomial, custom) so designers can tune without code changes. The Advanced Leveling System provides exactly this: 40+ experience curve algorithms, hand-drawn patterns, XP granting, level-up events, and save/load integration. Write your leveling logic once, reuse across projects.

Write level-up events as C# events or UnityEvents. When a player levels up, fire OnLevelUp(int newLevel). Subscribers handle stat increases, UI updates, and achievement checks. This decouples systems: the leveling system doesn't know about UI or achievements. For full API details, see the leveling API reference.

A Unity editor screenshot showing a leveling system inspector. A curve editor displays an exponential XP progression graph…

Writing Skill Systems with Cooldowns and Projectiles

Write skills as data-driven assets. Each skill has a type (projectile, AOE, buff/debuff), cooldown, cost, and targeting logic. Write the execution as a state machine: idle, casting, cooldown, ready. For projectile skills, write heat-seeking logic using vector math, not physics raycasts per frame. The Advanced Skill System implements this: projectile, AOE, and buff/debuff skills with cooldowns and heat-seeking, all modular.

Writing Inventory Systems with Data-Oriented Design

Write inventory as a flat array of item slots, not nested lists. Write currency, merchants, auction houses, and loot tables as separate modules sharing the same item database. The Inventory Management Suite uses data-oriented design: O(1) lookups, no per-frame allocations, and full integration with merchants and loot tables. Write your item database once; reuse everywhere.

ℹ️ Info

Write all RPG systems with save/load in mind. Serialize only deltas, not full state. A level 50 character with 200 inventory items should save in under 5ms. Write JSON or binary serialization, never PlayerPrefs for gameplay data.


Writing Multiplayer Networking: RPC, Lockstep, and Determinism

Writing multiplayer code requires determinism and minimal bandwidth. You write RPCs (Remote Procedure Calls) for actions, not state sync. You write lockstep for RTS, client-server for FPS, and rollback for fighting games. Each model has trade-offs.

Writing RPC Systems with Runtime Code Generation

Write RPCs as methods with attributes: [RPC] void FireWeapon(int playerId, Vector3 direction). The networking layer generates serialization code at runtime, avoiding reflection overhead. Write optimized serialization for common types (int, float, Vector3) using unsafe pointers or Span<byte>. RNet is a production RPC library for Unity 3D prioritizing reliable communication with runtime code generation and optimized serialization. Write your network layer once; it handles connection management, message serialization, and UI binding.

Write bandwidth budgets: 10KB/s per player for RTS, 50KB/s for FPS. Write delta compression for position updates. Write interpolation for remote entities to hide latency. A 100ms ping with 20Hz updates needs 5 frames of interpolation buffer.

Writing Deterministic Lockstep for Turn-Based Games

Write lockstep simulations with fixed-point math, not floats. Floats diverge across platforms. Write all game logic in a deterministic update loop: SimulateTick(int tick). Write input commands as struct with player ID, tick, and action. The Arcadus project uses lockstep networking with deterministic simulation. Write once, replay anywhere.

Networking ModelBandwidth (per player)Latency ToleranceBest For
RPC (Client-Server)20-50 KB/s100-200msFPS, action RPG
Lockstep (Deterministic)1-5 KB/s200-500msRTS, turn-based
Rollback (GGPO-style)10-30 KB/s50-150msFighting games
State Sync (Authoritative)50-100 KB/s50-100msMMO, survival

"Write networking as if every packet will be lost. Design for retransmission, ordering, and idempotency. The network is hostile; your code must be paranoid."

— RealSoft Games Engineering

Writing AI Integration and Dynamic NPC Dialogue

Writing AI for games means writing behavior trees, utility systems, or GOAP. For NPC dialogue, write integration with local LLMs. Write a chat module that connects to Ollama or LM Studio, streams responses, and injects context (player name, quest state, faction reputation). The LLM Chat Module does exactly this: connects Unity games to local LLM providers for dynamic NPC dialogue. Write prompts as templates; write response parsing as robust state machines.

Write AI performance budgets: behavior trees should evaluate in under 0.1ms per agent. Write 100 agents = 10ms, which is 16% of a 60 FPS frame. Write utility-based AI with cached scores, updated every 5-10 frames, not every frame. Write GOAP planners with A* over action space, cached and reused.

⚠️ Warning

Write LLM calls asynchronously. Never block the main thread waiting for a response. Write a queue for prompts, process one at a time, and cache responses for repeated queries. A 2-second LLM call will drop frames if synchronous.

A Unity scene showing a fantasy NPC with a dialogue UI overlay. A side panel displays a local LLM chat log with streaming…

Writing Technical Documentation for Unity Systems

Writing documentation is as critical as writing code. Write API references, integration guides, and tutorials. Write for three audiences: the developer integrating your asset, the designer tuning values, and the maintainer fixing bugs. Write code examples that compile. Write troubleshooting sections for common errors.

How Do I Write Documentation That Developers Actually Read?

Write in this order: quick start (5 minutes to first success), core concepts, API reference, advanced topics, troubleshooting. Write every public method with parameters, return values, and exceptions. Write a minimal working example for each feature. Write migration guides for version updates. The Unity Extensions Documentation Hub follows this structure: API references, tutorials, and integration guides for all RealSoft Games products.

Write documentation as code: use XML comments, generate HTML, and version with the asset. Write a changelog for every release. Write breaking changes in bold at the top. Write deprecation warnings with migration paths. A well-documented asset reduces support tickets by 60% and increases review scores by 1-2 stars.

💡 Tip

Write a README.md in every asset folder. Write the first line as the asset's purpose. Write the second line as the Unity version requirement. Write the third line as the installation step. Developers read the first three lines; make them count.


Writing for Developer Productivity: Tools and Workflows

Writing editor tools saves hundreds of hours. Write custom inspectors, property drawers, and asset post-processors. Write validation scripts that catch errors before build. Write automated tests for critical systems. Write CI/CD pipelines that build and test on every commit.

Write a Unity Extensions namespace with utility scripts: MathUtils, TransformExtensions, UIComponents. Write editor tools for common tasks: renaming assets, finding missing references, validating ScriptableObjects. Write property drawers for custom types like MinMaxRange or CurveReference. These small tools compound: 10 tools saving 5 minutes each per day = 50 minutes daily.

Write performance tests using Unity's Performance Testing package. Write benchmarks for hot paths: leveling calculations, inventory lookups, network serialization. Write assertions for allocation budgets: Assert.That(GC.Alloc, Is.EqualTo(0)). Write tests that run on every build. A regression in allocation is caught immediately, not in production.

"Write code for the developer who maintains it in six months. That developer is you. Write comments for why, not what. Write tests for edge cases, not happy paths."

— RealSoft Games Engineering

Frequently Asked Questions

Q: How do I write zero-allocation Unity code?

A: Write zero-allocation code by caching all references, pooling all objects, using structs over classes in hot paths, and avoiding LINQ, string concatenation, and boxing. Write GetComponent in Awake, never Update. Write object pools for bullets, enemies, and UI. Write arrays of structs instead of lists of classes. Verify with the Profiler's GC Alloc column; it should read 0B in steady state.

Q: What's the best way to write an RPG leveling system in Unity?

A: Write leveling as a pure function: GetXpForLevel(int level). Use ScriptableObjects for curves so designers can tune without code. Write level-up events to decouple systems. The Advanced Leveling System provides 40+ curve algorithms, XP granting, level-up events, and save/load, so you write integration, not infrastructure.

Q: How do I write multiplayer networking for Unity?

A: Write RPCs for actions, not state sync. Write lockstep for RTS, client-server for FPS. Write deterministic simulation with fixed-point math for lockstep. Use RNet for production RPC with runtime code generation and optimized serialization. Write bandwidth budgets: 10KB/s for RTS, 50KB/s for FPS.

Q: How do I write documentation for a Unity asset?

A: Write quick start first (5 minutes to first success), then core concepts, API reference, advanced topics, and troubleshooting. Write a minimal working example for each feature. Write XML comments and generate HTML. Write a changelog with breaking changes in bold. A well-documented asset reduces support tickets by 60%.

Q: What's the best way to write AI for NPC dialogue in Unity?

A: Write a chat module that connects to local LLMs like Ollama or LM Studio. Write prompts as templates with context injection (player name, quest state). Write asynchronous calls with a queue and response caching. The LLM Chat Module handles this integration, so you write dialogue content, not networking.

Q: How do I write modular game systems that integrate together?

A: Write each system as a self-contained module with a clean interface. Write events for cross-system communication. Write save/load for each module independently. Write data-oriented designs with O(1) lookups. The Inventory Management Suite and Advanced Skill System demonstrate this: separate modules that share an item database and event bus.


Writing Unity game systems that ship is a discipline. Write zero-allocation code, write modular RPG mechanics, write deterministic networking, and write documentation that developers actually read. Start with one system: write a pooled spawner, write a leveling curve, write an RPC. Measure with the Profiler. Write tests. Then write the next system. Each well-written system compounds: faster iteration, fewer bugs, happier players. For more Unity development guides, see RealSoft Games articles and the Unity tutorial.