---
description: Multiplayer and Networking
alwaysApply: false
---

# Multiplayer and Networking

Guidelines for building multiplayer games with Netcode for GameObjects.

## Core Principles

- Server is authoritative for all gameplay state; never trust the client
- Synchronize only gameplay state, not visual effects
- Design for latency from day one; add prediction and interpolation early
- Test with simulated latency and packet loss, not just localhost

## Data Flow

- Client sends input via **ServerRpc**
- Server validates, simulates, updates **NetworkVariables**
- Clients receive state, reconcile predictions, interpolate remote entities

## RPC and Sync Guidelines

| Type | Direction | Use For |
|------|-----------|---------|
| ServerRpc | Client -> Server | Player input, action requests |
| ClientRpc | Server -> Client(s) | VFX triggers, audio cues |
| NetworkVariable | Server -> All | Gameplay state (health, position) |

**Sync**: Position, health, score, equipped item, match timer
**Don't sync**: Particles, animation blends, footsteps, camera shake, UI animations

## Lag Compensation

| Technique | Purpose |
|-----------|---------|
| Client-side prediction | Responsive local movement; apply input immediately |
| Server reconciliation | Correct prediction errors from last confirmed state |
| Entity interpolation | Smooth remote entities; buffer 2-3 states |
| Lag compensation | Fair hit detection; rewind server to client view time |

## Network Testing

| Condition | Simulate | Expected |
|-----------|----------|----------|
| 50ms RTT | Typical broadband | Smooth with prediction |
| 150ms RTT | Mobile / cross-region | Noticeable but playable |
| 5% packet loss | Unstable WiFi | Interpolation hides gaps |

Use Unity Transport simulator or Clumsy/NetEm.

## Security

| Threat | Mitigation |
|--------|-----------|
| Speed hacking | Server validates movement delta per tick |
| Packet injection | Validate all ServerRpc params on server |
| State spoofing | Only server writes NetworkVariables |

## Common Pitfalls

**Trusting Client State**: Client sends `TakeDamageServerRpc(999)` and server applies directly. Server must calculate damage from weapon data and hit validation.

**Syncing Visual Data**: NetworkVariable for particle colors and animation params. Sync gameplay state; derive visuals locally.

**No Prediction on Owned Objects**: Waiting for server confirmation before moving local player. Apply input immediately, reconcile on server state arrival.
