←All patterns
Optimization

Spatial Partition

Bucket objects by where they are so "what is near me?" only looks at the neighbourhood, not the whole world.

What Is It?

Many game questions are spatial: which enemies are inside this explosion, which boids are close enough to flock with, which pickups can the magnet pull? The naive answer loops over every object and measures the distance — fine for 50 units, ruinous for 5,000 asking the same question each frame.

A spatial partition divides the world into regions and files each object under the region it occupies. The simplest version is a uniform grid: a Dictionary<Vector2Int, List<Unit>> keyed by cell. A query converts its bounds into a range of cells and only inspects objects stored in those cells.

Objects must tell the grid when they move to a different cell, but that is cheap — a remove and an add, and only when crossing a boundary. In return, neighbour queries go from O(n) per query to roughly the handful of objects in nearby cells. Quadtrees, octrees and BVHs are the adaptive cousins of the same idea.

When Is It Used?

Use it when many objects repeatedly query their surroundings: crowd steering, RTS target acquisition, bullet-hell collision, AI perception, proximity voice chat.

A uniform grid works best when objects are spread fairly evenly and have similar sizes. For very clumpy worlds or huge size differences, a quadtree adapts better.

If you only have a few dozen objects, or Unity physics queries like Physics.OverlapSphereNonAlloc already answer the question, the built-in broadphase is probably enough.

Interactive Demo

Click the controls and watch the objects collaborate. The console mirrors what the C# code below would log.

Spatial Partition Pattern
checks0found0avg grid0.0saved0%
0112020003422232020310320245230110011122
Grid0 / 60 checks
Brute force60 / 60 checks (avg)
Drag / tap the field to move the query · units re-bucketed: 0
Console
Press a button to see what happens…

Code

Assets / Scripts / Optimization/ SpatialPartition ›SpatialTester.cs
using System.Collections.Generic;
using UnityEngine;

namespace Patterns.Optimization.SpatialPartition
{
    /// <summary>
    /// Spawns wandering units, then every frame finds those within a radius
    /// of this object using the grid instead of scanning every unit.
    /// </summary>
    public class SpatialTester : MonoBehaviour
    {
        [SerializeField] private Unit unitPrefab;
        [SerializeField] private int unitCount = 500;
        [SerializeField] private float worldSize = 100f;
        [SerializeField] private float cellSize = 10f;
        [SerializeField] private float queryRadius = 8f;

        private SpatialGrid<Unit> grid;
        private readonly List<Unit> results = new();

        private void Awake()
        {
            grid = new SpatialGrid<Unit>(cellSize);

            for (int i = 0; i < unitCount; i++)
            {
                Vector2 p = new(Random.value * worldSize, Random.value * worldSize);
                Unit unit = Instantiate(unitPrefab, new Vector3(p.x, 0f, p.y), Quaternion.identity);
                unit.Init(grid, worldSize);
            }
        }

        private void Update()
        {
            Vector2 center = new(transform.position.x, transform.position.z);
            int checks = grid.Query(center, queryRadius, results);

            foreach (Unit unit in results)
                Debug.DrawLine(transform.position, unit.transform.position, Color.cyan);

            if (Time.frameCount % 60 == 0)
                Debug.Log($"Found {results.Count} with {checks} distance checks (brute force: {unitCount}).");
        }
    }
}
3 files · namespace Patterns.Optimization.SpatialPartitionC# · UTF-8 · LF

Before & After

Real-world smell: units that check every other unit to find a neighbour. Here is the code without the pattern, the refactored version, and the exact diff between them.

! What’s wrong with it?

Every Unit adds itself to a static all list, and FindNearest loops over that whole list each frame to find the closest unit inside senseRadius.

With 500 units that is 250,000 distance checks per frame, almost all of them against units on the other side of the map. Double the army and the cost quadruples: the classic O(n²) wall.

✓ What changed

  • The static all list is replaced by a shared SpatialGrid<Unit>, and the unit implements ISpatialItem.
  • Init files the unit under its starting cell, and Update calls grid.Move only when the unit crosses into a new cell.
  • FindNearest calls grid.Query first, so the loop only sees units in the cells that overlap senseRadius.
  • The distance check itself is unchanged; the grid only shrinks the list it runs over.
Unit.Before.cs → Unit.After.cs+21/−8
11 using System.Collections.Generic;
22 using UnityEngine;
33
44 namespace Patterns.Optimization.SpatialPartition
55 {
66 /// <summary>
7− /// Without a spatial partition: every unit scans every other unit each
8− /// frame to find its nearest neighbour. That is O(n²) per frame.
7+ /// With a spatial partition: each unit lives in a grid cell and only
8+ /// checks the units in the cells around it.
99 /// </summary>
10− public class Unit : MonoBehaviour
10+ public class Unit : MonoBehaviour, ISpatialItem
1111 {
1212 [SerializeField] private float speed = 4f;
1313 [SerializeField] private float senseRadius = 8f;
1414
15− private static readonly List<Unit> all = new();
15+ private static readonly List<Unit> nearby = new();
1616
17+ private SpatialGrid<Unit> grid;
18+ private Vector2Int cell;
1719 private Vector2 velocity;
1820 private float bounds;
1921
2022 public Vector2 Position => new(transform.position.x, transform.position.z);
2123 public Unit Nearest { get; private set; }
2224
23− public void Init(float worldSize)
25+ public void Init(SpatialGrid<Unit> owner, float worldSize)
2426 {
27+ grid = owner;
2528 bounds = worldSize;
2629 velocity = Random.insideUnitCircle.normalized * speed;
27− all.Add(this);
30+ cell = grid.CellOf(Position);
31+ grid.Add(this, cell);
2832 }
2933
3034 private void Update()
3135 {
3236 Vector2 p = Position + velocity * Time.deltaTime;
3337 if (p.x < 0f || p.x > bounds) velocity.x = -velocity.x;
3438 if (p.y < 0f || p.y > bounds) velocity.y = -velocity.y;
3539 p = new Vector2(Mathf.Clamp(p.x, 0f, bounds), Mathf.Clamp(p.y, 0f, bounds));
3640 transform.position = new Vector3(p.x, 0f, p.y);
3741
42+ // Re-bucket only when the cell actually changes.
43+ Vector2Int newCell = grid.CellOf(p);
44+ if (newCell != cell)
45+ {
46+ grid.Move(this, cell, newCell);
47+ cell = newCell;
48+ }
49+
3850 Nearest = FindNearest();
3951 }
4052
4153 private Unit FindNearest()
4254 {
4355 Unit best = null;
4456 float bestSq = senseRadius * senseRadius;
45− foreach (Unit other in all) // every unit, however far away
57+ grid.Query(Position, senseRadius, nearby);
58+ foreach (Unit other in nearby) // only units in the cells around us
4659 {
4760 if (other == this) continue;
4861 float sq = (other.Position - Position).sqrMagnitude;
4962 if (sq < bestSq) { bestSq = sq; best = other; }
5063 }
5164 return best;
5265 }
5366
54− private void OnDestroy() => all.Remove(this);
67+ private void OnDestroy() => grid?.Remove(this, cell);
5568 }
5669 }

Advantages & Disadvantages

+ Advantages

  • Turns neighbour searches from checking everything into checking a small local set.
  • A uniform grid is tiny to implement and has predictable, cache-friendly costs.
  • Works for non-physics data too — AI blackboards, audio emitters, fog-of-war reveals.

− Disadvantages

  • Objects must be kept in sync; forgetting to update a moved unit makes queries silently wrong.
  • Choosing a cell size is a trade-off: too small means many cells per query, too large means crowded cells.
  • Uses extra memory for buckets, and dense clusters in one cell degrade back towards brute force.

Tips

  1. 01Pick a cell size close to your most common query radius; then a query touches at most a 3×3 block of cells.
  2. 02Only re-bucket a unit when its cell coordinate actually changes — compare the old and new Vector2Int first.
  3. 03Reuse a results List<T> passed into the query instead of returning a new list, to keep the hot path allocation-free.
  4. 04The grid narrows candidates; still do the exact distance check (sqrMagnitude against radius²) on those candidates.
  5. 05For thousands of units, consider a flat-array grid with Burst and the Jobs system instead of a dictionary of lists.