←All patterns
Game Programming

Double Buffer

Read from a finished copy of the state and write into a second copy, then swap them, so an update never sees its own half-done work.

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.

Double Buffer Pattern
generation0alive8wrong cells0
Currentread · A
Nextwrite · B
⇄Swap() ×0
Console
Press a button to see what happens…

Code

Assets / Scripts / Game Programming/ DoubleBuffer ›LifeView.cs
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);
    }
}
3 files · namespace Patterns.Game Programming.DoubleBufferC# · UTF-8 · LF

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[,] cells becomes a DoubleBuffer<bool[,]> holding two arrays of the same size.
  • Step reads only from cells.Current (as read) and writes only into cells.Next (as write).
  • A single cells.Swap() at the end publishes the new generation; the indexer and Set read through Current.
  • CountNeighbours is unchanged: it already took the grid as a parameter, so it now receives the read buffer.
LifeGrid.Before.cs → LifeGrid.After.cs+12/−9
11 namespace Patterns.GameProgramming.DoubleBuffer
22 {
33 /// <summary>
4− /// Without Double Buffer: the grid is updated in place, so cells later in
5− /// the scan read neighbours that already belong to the next generation.
4+ /// With Double Buffer: every read comes from the finished generation and
5+ /// every write goes to the other buffer, then the two swap roles.
66 /// </summary>
77 public sealed class LifeGrid
88 {
9− private readonly bool[,] cells;
9+ private readonly DoubleBuffer<bool[,]> cells;
1010
1111 public int Width { get; }
1212 public int Height { get; }
1313 public int Generation { get; private set; }
1414
1515 public LifeGrid(int width, int height)
1616 {
1717 Width = width;
1818 Height = height;
19− cells = new bool[width, height];
19+ cells = new DoubleBuffer<bool[,]>(new bool[width, height], new bool[width, height]);
2020 }
2121
22− public bool this[int x, int y] => cells[x, y];
22+ public bool this[int x, int y] => cells.Current[x, y];
2323
24− public void Set(int x, int y, bool alive) => cells[x, y] = alive;
24+ public void Set(int x, int y, bool alive) => cells.Current[x, y] = alive;
2525
2626 public void Step()
2727 {
28+ bool[,] read = cells.Current;
29+ bool[,] write = cells.Next;
30+
2831 for (int y = 0; y < Height; y++)
2932 for (int x = 0; x < Width; x++)
3033 {
31− int n = CountNeighbours(cells, x, y);
32− // Bug: the left and upper neighbours were already overwritten.
33− cells[x, y] = n == 3 || (n == 2 && cells[x, y]);
34+ int n = CountNeighbours(read, x, y);
35+ write[x, y] = n == 3 || (n == 2 && read[x, y]);
3436 }
3537
38+ cells.Swap();
3639 Generation++;
3740 }
3841
3942 private int CountNeighbours(bool[,] grid, int x, int y)
4043 {
4144 int count = 0;
4245 for (int dy = -1; dy <= 1; dy++)
4346 for (int dx = -1; dx <= 1; dx++)
4447 {
4548 if (dx == 0 && dy == 0) continue;
4649 int nx = (x + dx + Width) % Width;
4750 int ny = (y + dy + Height) % Height;
4851 if (grid[nx, ny]) count++;
4952 }
5053 return count;
5154 }
5255 }
5356 }

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 Next keeps stale values from two steps ago.
  • Changes become visible one step later, a frame of latency that some systems (input, collisions) cannot afford.

Tips

  1. 01Swap references, never copy arrays. (current, next) = (next, current) is all Swap() needs.
  2. 02Make sure every cell of Next is assigned in the step; if you only write "changed" cells, clear or copy first.
  3. 03For large grids, combine it with NativeArray<T> and an IJobParallelFor: one job reads Current, writes Next, and the swap happens on the main thread after Complete().
  4. 04On the GPU, use two RenderTextures and Graphics.Blit(a, b, material), then swap the variables. Never read and write the same RenderTexture in one pass.
  5. 05Name the buffers by role (read/write), not by index, so nobody accidentally writes into the one being read.