←All patterns
Game Programming

Game Loop

Advance the game in steady time steps, decoupled from how fast the machine can render frames.

What Is It?

Every game runs a loop: read input, update the world, render, repeat. The hard part is time. Frames never take the same length; a phone hitting a thermal limit, a GC pause or a loading hitch can stretch one frame from 16 ms to 120 ms. If your simulation assumes every frame is equal, the game runs faster on fast machines and breaks on slow ones.

The fix is to separate the two clocks. Rendering happens as often as it can, with a variable delta. The simulation advances in fixed steps: an accumulator collects real elapsed time, and the loop runs as many 0.02 s steps as fit inside it, carrying the remainder to the next frame. Same inputs, same steps, same result, on any device.

Unity already owns the loop and gives you both clocks. Update runs once per rendered frame and Time.deltaTime tells you how long it was. FixedUpdate runs zero, one or several times per frame, each step exactly Time.fixedDeltaTime long, and the physics engine steps right after it. Time.maximumDeltaTime caps how much time a single frame may feed into that catch-up loop.

When Is It Used?

You use this pattern every day in Unity, whether you notice it or not: deciding whether code belongs in Update or FixedUpdate is a Game Loop decision. Rigidbody forces, MovePosition and custom physics go in the fixed step; input, cameras, UI and visual-only animation go in Update.

Write your own accumulator loop when you need determinism Unity does not give you: lockstep multiplayer, replays recorded as inputs, a turn-based simulation that should play out identically on every machine, or a server that ticks at 30 Hz independent of rendering.

Do not run gameplay at a fixed step just because it sounds "more correct". Character controllers, tweens and camera follow usually feel smoother in Update with Time.deltaTime, and stepping them in FixedUpdate without interpolation makes them visibly stutter on high-refresh displays.

Interactive Demo

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

Game Loop Pattern
deltaTime16 msframes0FixedUpdate0tunnelled0
slow-mo ×4
FixedUpdate
fixed 20 ms steps
Update × dt
one step per frame
stable
frame timelineUpdate()
bar = frame time · dots = fixed steps run
accumulator0.0 ms
0fixedDeltaTime = 20 ms100
Console
Press a button to see what happens…

Code

Assets / Scripts / Game Programming/ GameLoop ›LoopDriver.cs
using UnityEngine;

namespace Patterns.GameProgramming.GameLoop
{
    /// <summary>
    /// Hosts a custom fixed-step simulation inside Unity's player loop.
    /// Update runs once per rendered frame with a variable deltaTime;
    /// the runner turns that into equal 50 Hz steps.
    /// </summary>
    public class LoopDriver : MonoBehaviour
    {
        [SerializeField] private Transform ballView;
        [SerializeField] private float stepsPerSecond = 50f;
        [SerializeField] private float maxFrameDelta = 0.25f;

        private BallSimulation ball;
        private SimulationRunner runner;

        private void Awake()
        {
            ball = new BallSimulation(new Vector2(0f, 5f), Physics2D.gravity);
            runner = new SimulationRunner(ball.Step, 1f / stepsPerSecond, maxFrameDelta);
        }

        private void Update()
        {
            // Scaled time, so pausing with Time.timeScale = 0 also pauses the simulation.
            int steps = runner.Advance(Time.deltaTime);

            if (steps > 2)
                Debug.Log($"Slow frame: caught up with {steps} fixed steps");

            // Render between the previous and current state, so the ball moves
            // smoothly even when a frame ran zero or two steps.
            ballView.position = ball.Interpolated(runner.Alpha);
        }
    }
}
4 files · namespace Patterns.Game Programming.GameLoopC# · UTF-8 · LF

Before & After

Real-world smell: player movement that assumes every frame is 1/60 of a second. Here is the code without the pattern, the refactored version, and the exact diff between them.

! What’s wrong with it?

PlayerMovement moves transform.position by moveSpeed units every frame, spins the marker by a hard-coded 2f degrees per frame and calls body.AddForce for the boost straight from Update.

On a 144 Hz monitor the player runs more than twice as fast as on a 60 fps laptop, and on a 30 fps phone it crawls. The continuous boost force is applied once per rendered frame instead of once per physics step, so its strength depends on frame rate too, and writing to transform.position fights the Rigidbody instead of moving it through the physics engine.

✓ What changed

  • moveSpeed is now in units per second (6f) and is multiplied by Time.fixedDeltaTime; the marker spin uses markerSpin * Time.deltaTime.
  • Update only reads input into the input, boosting and jumpQueued fields; it no longer touches the rigidbody.
  • A new FixedUpdate moves the body with body.MovePosition and applies the boost force once per fixed step, so physics behaves the same at any frame rate.
  • The jump is queued in Update and consumed in FixedUpdate, so a one-frame GetButtonDown is never lost when a frame runs no physics step.
PlayerMovement.Before.cs → PlayerMovement.After.cs+23/−8
11 using UnityEngine;
22
33 namespace Patterns.GameProgramming.GameLoop
44 {
55 /// <summary>
6− /// Without a fixed timestep: speed is "units per frame" and physics is
7− /// pushed from Update. Feels right at 60 fps, and only at 60 fps.
6+ /// With Game Loop awareness: Update reads input and animates visuals with
7+ /// deltaTime; FixedUpdate moves the rigidbody once per fixed step.
88 /// </summary>
99 [RequireComponent(typeof(Rigidbody))]
1010 public class PlayerMovement : MonoBehaviour
1111 {
12− [SerializeField] private float moveSpeed = 0.1f; // units per frame
12+ [SerializeField] private float moveSpeed = 6f; // units per second
1313 [SerializeField] private float jumpForce = 5f;
1414 [SerializeField] private float thrust = 30f;
1515 [SerializeField] private Transform marker;
16+ [SerializeField] private float markerSpin = 120f; // degrees per second
1617
1718 private Rigidbody body;
19+ private Vector3 input;
20+ private bool boosting;
21+ private bool jumpQueued;
1822
1923 private void Awake() => body = GetComponent<Rigidbody>();
2024
2125 private void Update()
2226 {
2327 float x = Input.GetAxisRaw("Horizontal");
2428 float z = Input.GetAxisRaw("Vertical");
25− Vector3 input = Vector3.ClampMagnitude(new Vector3(x, 0f, z), 1f);
29+ input = Vector3.ClampMagnitude(new Vector3(x, 0f, z), 1f);
2630
27− marker.Rotate(0f, 2f, 0f);
31+ marker.Rotate(0f, markerSpin * Time.deltaTime, 0f);
2832
29− transform.position += input * moveSpeed;
33+ boosting = Input.GetKey(KeyCode.LeftShift);
3034
31− if (Input.GetKey(KeyCode.LeftShift))
35+ if (Input.GetButtonDown("Jump"))
36+ jumpQueued = true;
37+ }
38+
39+ private void FixedUpdate()
40+ {
41+ body.MovePosition(body.position + input * (moveSpeed * Time.fixedDeltaTime));
42+
43+ if (boosting)
3244 body.AddForce(transform.forward * thrust);
3345
34− if (Input.GetButtonDown("Jump"))
46+ if (jumpQueued)
47+ {
3548 body.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
49+ jumpQueued = false;
50+ }
3651 }
3752 }
3853 }

Advantages & Disadvantages

+ Advantages

  • Physics and gameplay become frame-rate independent: a 30 fps phone and a 144 Hz monitor play the same game.
  • Fixed steps keep integrators stable, so fast objects stop tunnelling through walls and springs stop exploding after a hitch.
  • A custom fixed-step loop is deterministic and easy to test: feed it the same deltas and inputs and it produces the same states.

− Disadvantages

  • When one step costs more than it simulates, the loop falls behind and runs even more steps next frame: the spiral of death. You must clamp the frame delta.
  • Rendering and simulation drift apart by up to one step, so without interpolation objects judder. Interpolating adds one step of visual latency.
  • Input read in FixedUpdate misses one-frame events like GetButtonDown, a classic source of "my jump sometimes does not fire" bugs.

Tips

  1. 01Never write transform.position += velocity; without * Time.deltaTime. Speeds should be in units per second, not units per frame.
  2. 02Read input in Update, store it in a field, and consume it in FixedUpdate. Clear one-shot flags (like a queued jump) only after the physics step used them.
  3. 03Set Rigidbody.interpolation to Interpolate on the player and anything the camera follows; it hides the gap between fixed steps and rendered frames.
  4. 04Keep Time.maximumDeltaTime reasonable (Unity defaults to 0.3333 s). Lower it if heavy scenes spiral; the game then slows down briefly instead of freezing.
  5. 05Changing Time.fixedDeltaTime changes physics cost directly: halving it doubles the number of physics steps per second. Profile before tuning it.