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.
Code
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);
}
}
}using System;
namespace Patterns.GameProgramming.GameLoop
{
/// <summary>
/// A fixed-timestep loop driven by an accumulator. Feed it the real length
/// of each frame; it calls the simulation in equal-sized steps, so the
/// result never depends on how fast or slow frames arrive.
/// </summary>
public sealed class SimulationRunner
{
private readonly Action<float> step;
private readonly float fixedDelta;
private readonly float maxFrameDelta;
private float accumulator;
public SimulationRunner(Action<float> step, float fixedDelta = 0.02f, float maxFrameDelta = 0.25f)
{
this.step = step ?? throw new ArgumentNullException(nameof(step));
this.fixedDelta = fixedDelta;
this.maxFrameDelta = maxFrameDelta;
}
public float FixedDelta => fixedDelta;
public long TotalSteps { get; private set; }
/// <summary>0..1: how far real time has moved past the last step. Use it to interpolate rendering.</summary>
public float Alpha => accumulator / fixedDelta;
/// <returns>How many fixed steps ran during this frame (0, 1 or several).</returns>
public int Advance(float frameDelta)
{
// Clamp huge frames (a breakpoint, a loading hitch) so we never try to
// catch up forever. This is what prevents the spiral of death.
if (frameDelta > maxFrameDelta)
frameDelta = maxFrameDelta;
accumulator += frameDelta;
int steps = 0;
while (accumulator >= fixedDelta)
{
step(fixedDelta);
accumulator -= fixedDelta;
steps++;
}
TotalSteps += steps;
return steps;
}
public void Reset() => accumulator = 0f;
}
}using UnityEngine;
namespace Patterns.GameProgramming.GameLoop
{
/// <summary>
/// The simulated state of a bouncing ball. Plain C#, no Unity callbacks:
/// the same sequence of Step calls always produces the same positions.
/// </summary>
public sealed class BallSimulation
{
private readonly Vector2 gravity;
private readonly float floorY;
private readonly float restitution;
public Vector2 Position;
public Vector2 Velocity;
public Vector2 PreviousPosition { get; private set; }
public BallSimulation(Vector2 start, Vector2 gravity, float floorY = 0f, float restitution = 0.9f)
{
Position = PreviousPosition = start;
this.gravity = gravity;
this.floorY = floorY;
this.restitution = restitution;
}
public void Step(float dt)
{
PreviousPosition = Position;
// Semi-implicit Euler: stable as long as dt stays small and constant.
Velocity += gravity * dt;
Position += Velocity * dt;
if (Position.y < floorY)
{
Position.y = floorY;
Velocity.y = -Velocity.y * restitution;
}
}
/// <summary>Blend between the last two steps for smooth rendering.</summary>
public Vector2 Interpolated(float alpha) => Vector2.Lerp(PreviousPosition, Position, alpha);
}
}using UnityEngine;
namespace Patterns.GameProgramming.GameLoop
{
/// <summary>
/// Unity's own two clocks used correctly: input and visuals in Update
/// (variable deltaTime), rigidbody movement and forces in FixedUpdate.
/// </summary>
[RequireComponent(typeof(Rigidbody))]
public class PlayerMotor : MonoBehaviour
{
[SerializeField] private float moveSpeed = 6f; // units per second
[SerializeField] private float jumpImpulse = 5f;
[SerializeField] private Transform selectionRing;
[SerializeField] private float ringSpinSpeed = 90f; // degrees per second
private Rigidbody body;
private Vector3 moveInput;
private bool jumpQueued;
private void Awake()
{
body = GetComponent<Rigidbody>();
body.interpolation = RigidbodyInterpolation.Interpolate;
}
private void Update()
{
moveInput = Vector3.ClampMagnitude(
new Vector3(Input.GetAxisRaw("Horizontal"), 0f, Input.GetAxisRaw("Vertical")), 1f);
// One-frame input must be caught here: this frame may run no FixedUpdate at all.
if (Input.GetButtonDown("Jump"))
jumpQueued = true;
// Purely visual motion: scale by deltaTime so it is frame-rate independent.
selectionRing.Rotate(0f, ringSpinSpeed * Time.deltaTime, 0f);
}
private void FixedUpdate()
{
// Runs every Time.fixedDeltaTime (0.02 s by default), 0..n times per frame.
body.MovePosition(body.position + moveInput * (moveSpeed * Time.fixedDeltaTime));
if (jumpQueued)
{
body.AddForce(Vector3.up * jumpImpulse, ForceMode.Impulse);
jumpQueued = false;
}
}
}
}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
moveSpeedis now in units per second (6f) and is multiplied byTime.fixedDeltaTime; the marker spin usesmarkerSpin * Time.deltaTime.Updateonly reads input into theinput,boostingandjumpQueuedfields; it no longer touches the rigidbody.- A new
FixedUpdatemoves the body withbody.MovePositionand applies the boost force once per fixed step, so physics behaves the same at any frame rate. - The jump is queued in
Updateand consumed inFixedUpdate, so a one-frameGetButtonDownis never lost when a frame runs no physics step.
using UnityEngine;
namespace Patterns.GameProgramming.GameLoop
{
/// <summary>
/// Without a fixed timestep: speed is "units per frame" and physics is
/// pushed from Update. Feels right at 60 fps, and only at 60 fps.
/// </summary>
[RequireComponent(typeof(Rigidbody))]
public class PlayerMovement : MonoBehaviour
{
[SerializeField] private float moveSpeed = 0.1f; // units per frame
[SerializeField] private float jumpForce = 5f;
[SerializeField] private float thrust = 30f;
[SerializeField] private Transform marker;
private Rigidbody body;
private void Awake() => body = GetComponent<Rigidbody>();
private void Update()
{
float x = Input.GetAxisRaw("Horizontal");
float z = Input.GetAxisRaw("Vertical");
Vector3 input = Vector3.ClampMagnitude(new Vector3(x, 0f, z), 1f);
marker.Rotate(0f, 2f, 0f);
transform.position += input * moveSpeed;
if (Input.GetKey(KeyCode.LeftShift))
body.AddForce(transform.forward * thrust);
if (Input.GetButtonDown("Jump"))
body.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
}
}using UnityEngine;
namespace Patterns.GameProgramming.GameLoop
{
/// <summary>
/// With Game Loop awareness: Update reads input and animates visuals with
/// deltaTime; FixedUpdate moves the rigidbody once per fixed step.
/// </summary>
[RequireComponent(typeof(Rigidbody))]
public class PlayerMovement : MonoBehaviour
{
[SerializeField] private float moveSpeed = 6f; // units per second
[SerializeField] private float jumpForce = 5f;
[SerializeField] private float thrust = 30f;
[SerializeField] private Transform marker;
[SerializeField] private float markerSpin = 120f; // degrees per second
private Rigidbody body;
private Vector3 input;
private bool boosting;
private bool jumpQueued;
private void Awake() => body = GetComponent<Rigidbody>();
private void Update()
{
float x = Input.GetAxisRaw("Horizontal");
float z = Input.GetAxisRaw("Vertical");
input = Vector3.ClampMagnitude(new Vector3(x, 0f, z), 1f);
marker.Rotate(0f, markerSpin * Time.deltaTime, 0f);
boosting = Input.GetKey(KeyCode.LeftShift);
if (Input.GetButtonDown("Jump"))
jumpQueued = true;
}
private void FixedUpdate()
{
body.MovePosition(body.position + input * (moveSpeed * Time.fixedDeltaTime));
if (boosting)
body.AddForce(transform.forward * thrust);
if (jumpQueued)
{
body.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
jumpQueued = false;
}
}
}
}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
FixedUpdatemisses one-frame events likeGetButtonDown, a classic source of "my jump sometimes does not fire" bugs.
Tips
- 01Never write
transform.position += velocity;without* Time.deltaTime. Speeds should be in units per second, not units per frame. - 02Read input in
Update, store it in a field, and consume it inFixedUpdate. Clear one-shot flags (like a queued jump) only after the physics step used them. - 03Set
Rigidbody.interpolationtoInterpolateon the player and anything the camera follows; it hides the gap between fixed steps and rendered frames. - 04Keep
Time.maximumDeltaTimereasonable (Unity defaults to 0.3333 s). Lower it if heavy scenes spiral; the game then slows down briefly instead of freezing. - 05Changing
Time.fixedDeltaTimechanges physics cost directly: halving it doubles the number of physics steps per second. Profile before tuning it.