What Is It?
Double Buffer keeps two copies of some state. During a step, everyone reads from Current and all writes go to Next. When the step is complete, Swap() flips the two references and the new state becomes visible all at once.
The problem it solves is order dependence. If a cellular automaton updates its grid in place, the cell at (5,3) is computed from neighbours that were already advanced to the next generation, while the cell at (4,3) saw the old ones. The result depends on the loop direction, not on the rules.
You use this every frame without thinking about it: Unity renders into a back buffer while the front buffer is on screen, and presents them with a swap. On the GPU, simulations such as fluid, blur or reaction-diffusion do the same with two RenderTextures, reading one in a shader and writing the other ("ping-pong").
When Is It Used?
Use it when many elements update "simultaneously" from shared state: Game of Life, heat or water spreading over tiles, influence maps, boids that must all react to last frame's positions.
It also fits when one system writes state that another reads incrementally, and the reader must never see a half-written result: a generated level built over several frames, or a job writing data the main thread consumes.
Skip it when updates are genuinely independent (each element only reads itself), or when the order is part of the design. A second buffer costs memory and a swap, and buys nothing if nobody reads mid-update.
Interactive Demo
Click the controls and watch the objects collaborate. The console mirrors what the C# code below would log.
Code
using UnityEngine;
namespace Patterns.GameProgramming.DoubleBuffer
{
/// <summary>
/// Steps the simulation on a fixed tick and draws Current into a texture.
/// The view never sees a half-written generation.
/// </summary>
public class LifeView : MonoBehaviour
{
[SerializeField] private int width = 64;
[SerializeField] private int height = 36;
[SerializeField] private float stepsPerSecond = 8f;
[SerializeField] private Renderer target;
private LifeGrid grid;
private Texture2D texture;
private Color32[] pixels;
private float timer;
private void Awake()
{
grid = new LifeGrid(width, height);
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
grid.Set(x, y, Random.value < 0.25f);
texture = new Texture2D(width, height, TextureFormat.RGBA32, false) { filterMode = FilterMode.Point };
pixels = new Color32[width * height];
target.material.mainTexture = texture;
}
private void Update()
{
timer += Time.deltaTime;
if (timer < 1f / stepsPerSecond) return;
timer = 0f;
grid.Step();
Draw();
}
private void Draw()
{
for (int y = 0; y < height; y++)
for (int x = 0; x < width; x++)
pixels[y * width + x] = grid[x, y] ? new Color32(120, 255, 180, 255) : new Color32(12, 14, 22, 255);
texture.SetPixels32(pixels);
texture.Apply(false);
}
private void OnDestroy() => Destroy(texture);
}
}namespace Patterns.GameProgramming.DoubleBuffer
{
/// <summary>
/// Conway's Game of Life on a wrapping grid. Every cell of the new
/// generation is computed only from the previous generation.
/// </summary>
public sealed class LifeGrid
{
private readonly DoubleBuffer<bool[,]> cells;
public int Width { get; }
public int Height { get; }
public int Generation { get; private set; }
public LifeGrid(int width, int height)
{
Width = width;
Height = height;
cells = new DoubleBuffer<bool[,]>(new bool[width, height], new bool[width, height]);
}
public bool this[int x, int y] => cells.Current[x, y];
public void Set(int x, int y, bool alive) => cells.Current[x, y] = alive;
public void Step()
{
bool[,] read = cells.Current;
bool[,] write = cells.Next;
for (int y = 0; y < Height; y++)
for (int x = 0; x < Width; x++)
{
int n = CountNeighbours(read, x, y);
// Reads come from 'read' only, so the scan order cannot matter.
write[x, y] = n == 3 || (n == 2 && read[x, y]);
}
cells.Swap();
Generation++;
}
private int CountNeighbours(bool[,] grid, int x, int y)
{
int count = 0;
for (int dy = -1; dy <= 1; dy++)
for (int dx = -1; dx <= 1; dx++)
{
if (dx == 0 && dy == 0) continue;
int nx = (x + dx + Width) % Width;
int ny = (y + dy + Height) % Height;
if (grid[nx, ny]) count++;
}
return count;
}
}
}namespace Patterns.GameProgramming.DoubleBuffer
{
/// <summary>
/// Two copies of the same state. Readers only see Current; the writer
/// fills Next, then Swap() publishes it in one cheap reference flip.
/// </summary>
public sealed class DoubleBuffer<T>
{
private T current;
private T next;
public DoubleBuffer(T first, T second)
{
current = first;
next = second;
}
/// <summary>The finished state of the last step. Read-only by convention.</summary>
public T Current => current;
/// <summary>The state being written for the next step.</summary>
public T Next => next;
/// <summary>No copying: the two buffers just trade roles.</summary>
public void Swap() => (current, next) = (next, current);
}
}Before & After
Real-world smell: a grid simulation that updates its cells in place. Here is the code without the pattern, the refactored version, and the exact diff between them.
! What’s wrong with it?
LifeGrid.Step loops over cells and writes each new value straight back into the same array. By the time it reaches a cell, its left and upper neighbours already hold next-generation values.
Gliders fall apart, blinkers stop blinking, and flipping the loop direction gives different results. The bug is subtle because the grid still "looks alive", so it tends to survive until a designer builds a level that depends on a known pattern.
✓ What changed
- The single
bool[,] cellsbecomes aDoubleBuffer<bool[,]>holding two arrays of the same size. Stepreads only fromcells.Current(asread) and writes only intocells.Next(aswrite).- A single
cells.Swap()at the end publishes the new generation; the indexer andSetread throughCurrent. CountNeighboursis unchanged: it already took the grid as a parameter, so it now receives the read buffer.
namespace Patterns.GameProgramming.DoubleBuffer
{
/// <summary>
/// Without Double Buffer: the grid is updated in place, so cells later in
/// the scan read neighbours that already belong to the next generation.
/// </summary>
public sealed class LifeGrid
{
private readonly bool[,] cells;
public int Width { get; }
public int Height { get; }
public int Generation { get; private set; }
public LifeGrid(int width, int height)
{
Width = width;
Height = height;
cells = new bool[width, height];
}
public bool this[int x, int y] => cells[x, y];
public void Set(int x, int y, bool alive) => cells[x, y] = alive;
public void Step()
{
for (int y = 0; y < Height; y++)
for (int x = 0; x < Width; x++)
{
int n = CountNeighbours(cells, x, y);
// Bug: the left and upper neighbours were already overwritten.
cells[x, y] = n == 3 || (n == 2 && cells[x, y]);
}
Generation++;
}
private int CountNeighbours(bool[,] grid, int x, int y)
{
int count = 0;
for (int dy = -1; dy <= 1; dy++)
for (int dx = -1; dx <= 1; dx++)
{
if (dx == 0 && dy == 0) continue;
int nx = (x + dx + Width) % Width;
int ny = (y + dy + Height) % Height;
if (grid[nx, ny]) count++;
}
return count;
}
}
}namespace Patterns.GameProgramming.DoubleBuffer
{
/// <summary>
/// With Double Buffer: every read comes from the finished generation and
/// every write goes to the other buffer, then the two swap roles.
/// </summary>
public sealed class LifeGrid
{
private readonly DoubleBuffer<bool[,]> cells;
public int Width { get; }
public int Height { get; }
public int Generation { get; private set; }
public LifeGrid(int width, int height)
{
Width = width;
Height = height;
cells = new DoubleBuffer<bool[,]>(new bool[width, height], new bool[width, height]);
}
public bool this[int x, int y] => cells.Current[x, y];
public void Set(int x, int y, bool alive) => cells.Current[x, y] = alive;
public void Step()
{
bool[,] read = cells.Current;
bool[,] write = cells.Next;
for (int y = 0; y < Height; y++)
for (int x = 0; x < Width; x++)
{
int n = CountNeighbours(read, x, y);
write[x, y] = n == 3 || (n == 2 && read[x, y]);
}
cells.Swap();
Generation++;
}
private int CountNeighbours(bool[,] grid, int x, int y)
{
int count = 0;
for (int dy = -1; dy <= 1; dy++)
for (int dx = -1; dx <= 1; dx++)
{
if (dx == 0 && dy == 0) continue;
int nx = (x + dx + Width) % Width;
int ny = (y + dy + Height) % Height;
if (grid[nx, ny]) count++;
}
return count;
}
}
}Advantages & Disadvantages
+ Advantages
- Results are deterministic and independent of iteration order, which makes the simulation easy to reason about and parallelise.
- Readers always see a complete, consistent state; there is no "tearing" halfway through a step.
- The swap is a reference flip, so publishing a whole new state is O(1).
− Disadvantages
- Twice the memory for the buffered state, which matters for large grids or textures.
- Every element must be written each step, or
Nextkeeps stale values from two steps ago. - Changes become visible one step later, a frame of latency that some systems (input, collisions) cannot afford.
Tips
- 01Swap references, never copy arrays.
(current, next) = (next, current)is allSwap()needs. - 02Make sure every cell of
Nextis assigned in the step; if you only write "changed" cells, clear or copy first. - 03For large grids, combine it with
NativeArray<T>and anIJobParallelFor: one job readsCurrent, writesNext, and the swap happens on the main thread afterComplete(). - 04On the GPU, use two
RenderTextures andGraphics.Blit(a, b, material), then swap the variables. Never read and write the sameRenderTexturein one pass. - 05Name the buffers by role (
read/write), not by index, so nobody accidentally writes into the one being read.