DEV Community

Cover image for Netcode for Unity Multiplayer: Client-Side Prediction and Lag Compensation Explained
Matthew Anderson
Matthew Anderson

Posted on

Netcode for Unity Multiplayer: Client-Side Prediction and Lag Compensation Explained

A player presses the move key. On a single-player build, the character moves on the next frame. In a server-authoritative multiplayer build, that input has to reach the server, get simulated, and come back before anything is confirmed. On a 60ms round trip that is roughly four frames of delay at 60fps. On a mobile connection it can be fifteen.

However, players read that delay as the game feeling heavy or unresponsive. They rarely report it as latency, so it usually arrives as “the controls feel wrong”.

Three techniques handle it: client-side prediction, server reconciliation and entity interpolation. A fourth, lag compensation, deals with hit detection. They are not alternatives. A shipped multiplayer game normally runs all four at once, and each one solves a different half of the problem.

This writeup covers how they fit together in Unity, with the parts that break in practice. The code below uses Netcode for GameObjects, though the same structure applies to Mirror, Fish-Net or a custom transport. The pattern is the same on mobile and on PC. Only the numbers change.

Why naive input forwarding fails

The simplest server-authoritative loop looks like this. The client sends input. The server simulates and broadcasts the result. The client renders what it receives.

It is correct, and it stops feeling responsive above about 30ms. Every action waits for a round trip, and local movement stops being frame-accurate. Worse, the delay is not constant, so the character feels different as the network moves around. That makes the network model a scoping decision rather than a polish task. Teams planning game development services around a multiplayer title settle it before production starts, because the movement code is built on top of it.

Client-side prediction

Prediction means the client simulates its own input immediately and does not wait for confirmation. The server stays authoritative. The client simply assumes it will agree.

Two things make this work. First, the movement code must be deterministic and run on a fixed timestep, so the same input produces the same result on both machines. Second, every input must be numbered and kept until the server acknowledges it.

csharp
struct InputCmd {
public uint tick;
public Vector2 move;
public bool jump;
}

readonly List _pending = new();
uint _tick;

void FixedUpdate() {
if (!IsOwner) return;

var cmd = new InputCmd {
    tick = _tick++,
    move = ReadMoveAxis(),
    jump = ReadJump()
};

_pending.Add(cmd);
SimulateStep(cmd, Time.fixedDeltaTime);  // predict locally
SendInputToServer(cmd);                  // then tell the server
Enter fullscreen mode Exit fullscreen mode

}

SimulateStep has to be the only place movement happens. The moment physics, animation events or a character controller mutate position outside it, prediction and the server drift apart and nothing below will fix it. Breaking that rule is a common cause of rework later.

Server reconciliation

The server runs the same SimulateStep on the inputs it receives, then sends back the resulting state with the tick number it last processed. The client compares that state against what it predicted for the same tick.

If they match, there is nothing to do. If they do not, the client snaps to the server state and replays every input newer than the acknowledged tick.

csharp
void OnServerState(uint ackTick, Vector3 pos, Vector3 vel) {
_pending.RemoveAll(c => c.tick <= ackTick);

if ((pos - PredictedPositionAt(ackTick)).sqrMagnitude < 0.0001f) return;

ApplyState(pos, vel);                    // rewind
foreach (var c in _pending)              // replay
    SimulateStep(c, Time.fixedDeltaTime);
Enter fullscreen mode Exit fullscreen mode

}

Three details matter here. First, use a squared-distance threshold rather than an exact comparison, because floating point will not match across platforms. Keep the pending buffer bounded, because a client that stops receiving state will otherwise replay forever and stall the main thread. And log how often reconciliation corrects by more than a few centimetres. A rising correction rate is the earliest signal that the simulation has diverged.

Entity interpolation for everyone else

Prediction applies to the local player only. Remote players arrive as discrete snapshots at the server tick rate, often 20 or 30 per second, and rendering those directly produces visible stepping.

The fix is to render remote entities slightly in the past, interpolating between the two snapshots that bracket the render time. The buffer needs one snapshot interval plus the jitter you expect. At a 20Hz send rate, 100ms is a common starting point. Unity’s own client-side interpolation documentation describes the buffering model and the tradeoff it carries.

csharp
float renderTime = NetworkTime - InterpolationDelay;
var (a, b) = _snapshots.Bracket(renderTime);
float t = Mathf.InverseLerp(a.time, b.time, renderTime);
transform.position = Vector3.Lerp(a.pos, b.pos, t);

Still, the cost is real and unavoidable. Remote players are drawn where they were, not where they are. That is exactly the problem the next section solves.

Lag compensation for hit detection

Because of interpolation, a shooting client aims at a position that is already stale on the server. If the server validates the shot against current positions, well-aimed shots miss, and the complaint arrives as “the hit detection is broken”.

So lag compensation makes the server rewind instead. It keeps a short history of every entity’s collider position, then validates the shot against the world as that client saw it. Valve’s Source multiplayer networking page describes this model in detail, and most modern engines implement a version of it.

csharp
bool ValidateShot(ulong shooter, uint clientTick, Ray ray) {
float rewindTo = TickToTime(clientTick) - GetInterpolationDelay(shooter);
using var _ = _history.Rewind(rewindTo); // move colliders back
return Physics.Raycast(ray, out var hit, MaxRange) && IsTarget(hit);
}

Also, cap the rewind window. Something between 200 and 500ms covers normal play. Past that, high-latency clients start landing shots that look impossible to everyone else, and favouring the shooter stops being fair.

What to actually tune

Four numbers decide how the game feels, and they interact. Set the latency target first, then pick the stack to match, since that order is how Unity multiplayer builds get scoped.

Server tick rate sets the simulation floor. 30Hz suits most co-op and casual titles. 60Hz is normal for competitive action, and the bandwidth cost scales roughly in line with it.

Next, snapshot send rate sits apart from tick rate, and it is usually lower. Interpolation delay follows from it, so raising one means raising the other.

Input redundancy covers packet loss. Sending the last three or four commands in each packet costs very little. Still, it removes most single-loss hitches, which matters more on mobile than it sounds.

Correction threshold decides how twitchy the local player looks. Set it too tight and the character vibrates under normal float error. Set it too loose and cheating becomes easy. One centimetre is a reasonable starting value, then tuned against recorded sessions.

Test under conditions that resemble reality

Testing on localhost does not test the netcode. Two clients on the same machine have no latency, no jitter and no loss, and no player runs under those conditions.

Unity ships a Network Simulator in the Multiplayer Tools package. Use it, and run at least three profiles: 50ms with low jitter, 150ms with 30ms jitter, and 250ms with 2% loss.

Device spread matters as much as the connection. Android and iOS game builds already get tested across low, mid and high-end handsets, so the network profiles belong in the same matrix. Add one more for a handover between cells: a one-second stall, then a burst of queued packets. That burst is what exposes an unbounded input buffer.

Then record the correction rate, the replay cost per frame and the snapshot buffer depth during each run. Those three numbers show whether the netcode is healthy before players report a problem.

Short checklist

Keep all movement inside one deterministic fixed-step function. Number every input and keep it until acknowledged. Snap and replay instead of smoothing a correction. Interpolate remote entities and accept the delay. Rewind on the server for hit validation, with a capped window. Then test with latency, jitter and loss before anyone outside the team plays it.

None of this is advanced work. It is the baseline a multiplayer build needs before it meets real network conditions.

Top comments (0)