Architecting O(1) performance for Unity games. A deep dive from brute-force chaos to million-particle optimization.
Understanding the geometry of optimization.
In a standard, naive collision or proximity system, every object checks every other object. This is O(N²) complexity. At small scales, it's fine. At game-scale, it's a death sentence.
Toggle the Spatial Hash mode above. Watch the lines collapse. By only checking objects in the same "neighborhood," we reduce the workload from thousands of checks to a handful of clustered tests.
Imagine 1,000 bullets and 100 enemies. A brute-force system doesn't care if a bullet is 1,000 meters away; it still runs the distance math. Spatial Hashing filters out the irrelevant noise before the math even starts.
By dividing the world into a fixed grid of "buckets," we can map any 3D coordinate to a specific bucket in constant time. This is the foundation of almost every modern physics engine.
Tuning the Cell Size is critical. If cells are too small, objects span many buckets. If they are too large, we check too many irrelevant objects. The goal is to maximize the Optimization % shown above.
Solving the Garbage Collection nightmare in Unity.
In C#, calling new List<T>() in an Update loop creates "Garbage." When Unity's Garbage Collector runs to clean this up, your game stutters. We solve this by recycling memory.
Stack<List<T>>.Clear() the list and push it back onto the stack.// The internal pooling logic
private Stack<List<T>> _pool = new();
private List<T> GetNewList() {
return _pool.Count > 0 ? _pool.Pop() : new List<T>();
}
private void RecycleList(List<T> list) {
list.Clear(); // Critical: keep the capacity, dump the items
_pool.Push(list);
}
Watch how the hash populates buckets in real-time. The intensity of the color represents how many entities are fighting for attention in that specific memory address.
Data-Oriented Design and Cache Locality.
For the ultimate performance (as seen in Matthias Müller's Ten Minute Physics), we ditch Dictionaries entirely. We move to Flat Arrays.
Iterate all objects once to count how many fall into each cell. No allocations, just integer increments.
Calculate starting offsets for every cell. This creates a "Map" of contiguous memory for your objects.
When you use List<T>, your data is scattered across RAM. The CPU has to "jump" around to find it. When you use Spatial Sorting, your data is lined up perfectly. The CPU pre-fetches the data before you even ask for them.
// Contiguous memory structure
NativeArray<int> cellStart; // Offsets into the object array
NativeArray<int> sortedObjects; // Objects sorted by their CellID
// Reading a cell is now a single, contiguous memory sweep:
int start = cellStart[cellID];
int end = cellStart[cellID + 1];
for (int i = start; i < end; i++) {
Process(sortedObjects[i]); // Ultra-fast!
}
Burst, Jobs, and Parallel Power.
Spatial hashing is embarrassingly parallel. By using Unity's NativeMultiHashMap and the Burst Compiler, you can move these checks off the main thread and into high-speed C++ level machine code.
Use NativeMultiHashMap.ParallelWriter to populate the grid across all CPU cores simultaneously.
The compiler optimizes the spatial math into SIMD instructions, checking multiple objects per CPU cycle.
[BurstCompile]
struct SpatialQueryJob : IJobParallelFor {
[ReadOnly] public NativeMultiHashMap<int, EntityData> hash;
public void Execute(int index) {
// Run proximity checks at 100x speed
}
}
Pixel Pickup: A real-time stress test.
Every floating pixel and enemy in the arena above is registered into a custom Spatial Hash. The ship queries its local cells to attract pixels (Magnet) and bullets query their cells to destroy enemies. The result is a chaotic experience running at a solid 60fps.
Ready-to-use API and modules for your Unity projects.
The generic, non-allocating 3D hash engine. Support for AABBs, Sphere queries, and Bucket Pooling.
VIEW SOURCE →A plug-and-play module for PurrNet, FishNet, and Mirror. Optimized Area of Interest management.
VIEW SOURCE →The logic behind CellGen. Handle portal-based visibility and room-to-room state synchronization.
VIEW SOURCE →Complete Unity samples including the Collision, Pathfinding, and World Streaming demos from this tutorial.
BROWSE SAMPLES →Get the entire Masterclass project, including the visualizers and the game arena code.
git clone https://github.com/TrentSterling/spatialhash.git
Perfect for PurrNet. Synchronize only the entities in a player's spatial "bubble." Save 90% of your network bandwidth.
Solve Mikkel's "Room Connectivity" problem. Instantly find "Which room am I in?" and propagate state through connected portals in $O(1)$.