Netcode for GameObjects
Netcode for GameObjects (NGO) (com.unity.netcode.gameobjects) is Unity's high-level networking library for GameObject-based games: co-op games, small competitive games, party games. It sits on Unity Transport (UDP, with optional relay and WebSockets) and gives you networked objects, synchronized variables and remote procedure calls. Unity 6 projects use NGO 2.x.
Core pieces
| Piece | Role |
|---|---|
| NetworkManager | one per game: starts host/server/client, holds the transport and the list of network prefabs |
| UnityTransport | the transport component: address, port, relay settings |
| NetworkObject | marks a GameObject as networked; spawned by the server, mirrored on clients |
| NetworkBehaviour | a MonoBehaviour with networking: IsServer, IsOwner, IsClient, OnNetworkSpawn, RPCs |
| NetworkVariable<T> | a value the server (or owner) writes and every client receives |
| NetworkTransform | synchronizes position/rotation/scale, server- or owner-authoritative |
A host is a server and a client in the same process: the common setup for co-op games without dedicated servers.
A networked player
using Unity.Netcode;
using UnityEngine;
public class NetPlayer : NetworkBehaviour
{
// Everyone can read; only the server writes (the default).
public NetworkVariable<int> Score = new(0);
public NetworkVariable<Color> Tint = new(Color.white, NetworkVariableReadPermission.Everyone,
NetworkVariableWritePermission.Owner);
public override void OnNetworkSpawn()
{
Score.OnValueChanged += (oldValue, newValue) => Debug.Log(quot;{name} score {oldValue} -> {newValue}");
if (IsOwner) Tint.Value = Random.ColorHSV(); // the owner may write its own tint
}
void Update()
{
if (!IsOwner) return; // only drive your own player
if (UnityEngine.InputSystem.Keyboard.current.spaceKey.wasPressedThisFrame)
RequestCollectRpc(transform.position);
}
// Client -> server: a request, not a command. The server decides.
[Rpc(SendTo.Server)]
void RequestCollectRpc(Vector3 claimedPosition, RpcParams rpcParams = default)
{
var coin = CoinRegistry.NearestTo(claimedPosition, 1.5f);
if (coin == null) return; // reject impossible claims
coin.NetworkObject.Despawn();
Score.Value += 1;
PlayCollectEffectRpc(coin.transform.position);
}
// Server -> everyone: cosmetic effect.
[Rpc(SendTo.ClientsAndHost)]
void PlayCollectEffectRpc(Vector3 at) { /* particles + sound */ }
}RPC methods must be marked [Rpc(SendTo.…)] and have a name ending in Rpc. (Older NGO code uses [ServerRpc] and [ClientRpc], which still exist.) Start a session from UI buttons:
NetworkManager.Singleton.StartHost(); // or StartServer() / StartClient()
// spawning (server only): Instantiate(prefab).GetComponent<NetworkObject>().Spawn();Authority: what a model shows
The golden rule of multiplayer: the server is the authority. Clients send inputs and requests; the server validates and changes state; state flows back as replicated variables. The model below runs a server and two clients with 2 ticks of latency each way. Client B cheats by claiming a coin far from where it really is:
using System;
using System.Collections.Generic;
var net = new Network(latencyTicks: 2);
var server = new Server(net);
var a = new Client("A", net); var b = new Client("B", net);
for (int tick = 0; tick <= 7; tick++)
{
net.Now = tick;
if (tick == 0) a.Send(new Msg("CollectRpc", "A", CoinId: 1, ClaimedX: 4.8)); // near coin 1 (x=5)
if (tick == 1) b.Send(new Msg("CollectRpc", "B", CoinId: 2, ClaimedX: 30.0)); // coin 2 is at x=12: cheat
net.Deliver(tick, server, new[] { a, b });
}
Console.WriteLine(quot;server truth: A={server.Score["A"]} B={server.Score["B"]}, coins left [{string.Join(", ", server.Coins.Keys)}]");
Console.WriteLine(quot;client views: A sees A={a.Scores.GetValueOrDefault("A")}, B sees A={b.Scores.GetValueOrDefault("A")}");
record Msg(string Kind, string Player, int CoinId = 0, double ClaimedX = 0, int Value = 0);
class Network
{
readonly int latency; readonly List<(int At, string To, Msg M)> inFlight = new();
public int Now;
public Network(int latencyTicks) => latency = latencyTicks;
public void Send(string to, Msg m) => inFlight.Add((Now + latency, to, m));
public void Deliver(int tick, Server s, Client[] clients)
{
foreach (var f in inFlight.FindAll(x => x.At == tick))
{
inFlight.Remove(f);
if (f.To == "server") s.Receive(tick, f.M);
else Array.Find(clients, c => c.Name == f.To)!.Receive(tick, f.M);
}
}
}
class Server
{
readonly Network net;
public readonly Dictionary<string, int> Score = new() { ["A"] = 0, ["B"] = 0 };
public readonly SortedDictionary<int, double> Coins = new() { [1] = 5.0, [2] = 12.0, [3] = 20.0 };
readonly Dictionary<string, double> playerX = new() { ["A"] = 4.9, ["B"] = 0.5 }; // server's own simulation
public Server(Network n) => net = n;
public void Receive(int tick, Msg m)
{
if (m.Kind != "CollectRpc") return;
bool exists = Coins.TryGetValue(m.CoinId, out double coinX);
bool inReach = exists && Math.Abs(playerX[m.Player] - coinX) <= 1.5; // check the SERVER's position, not the claim
Console.WriteLine(quot;tick {tick}: server got {m.Player}'s claim on coin {m.CoinId} -> {(inReach ? "accepted" : "rejected")}");
if (!inReach) return;
Coins.Remove(m.CoinId);
Score[m.Player]++;
foreach (var c in new[] { "A", "B" }) // replicate the NetworkVariable
net.Send(c, new Msg("ScoreChanged", m.Player, Value: Score[m.Player]));
}
}
class Client
{
public readonly string Name; readonly Network net;
public readonly Dictionary<string, int> Scores = new();
public Client(string name, Network n) { Name = name; net = n; }
public void Send(Msg m) { Console.WriteLine(quot; {Name} sends {m.Kind}(coin {m.CoinId}, x={m.ClaimedX})"); net.Send("server", m); }
public void Receive(int tick, Msg m)
{
Scores[m.Player] = m.Value;
Console.WriteLine(quot;tick {tick}: client {Name} sees {m.Player} score = {m.Value}");
}
} A sends CollectRpc(coin 1, x=4.8)
B sends CollectRpc(coin 2, x=30)
tick 2: server got A's claim on coin 1 -> accepted
tick 3: server got B's claim on coin 2 -> rejected
tick 4: client A sees A score = 1
tick 4: client B sees A score = 1
server truth: A=1 B=0, coins left [2, 3]
client views: A sees A=1, B sees A=1
Notice the round trip: A's coin is confirmed on A's screen 4 ticks after the press. Real games hide that with client-side prediction (play the effect immediately, correct if the server disagrees) and interpolation of other players. Those techniques, plus lag compensation and rollback, are the subject of the Multiplayer Game Networking course.
Testing locally
- Multiplayer Play Mode (package
com.unity.multiplayer.playmode) runs extra editor "virtual players" from the same project, so you can test host and clients without building. - Network Simulator (from the Multiplayer Tools package) adds artificial latency and packet loss. Test with 100–200 ms; everything works at 0 ms.
- Builds connect with
UnityTransport.SetConnectionData("127.0.0.1", 7777).
Other options
| Library | Notes |
|---|---|
| Netcode for Entities | Unity's ECS networking with prediction and rollback built in; for fast-paced shooters, bigger scale |
| Mirror | open-source, mature, large community, API close to old UNet |
| FishNet | open-source, feature-rich (prediction, lag compensation) |
| Photon (Fusion, PUN, Quantum) | commercial, hosted relay/cloud; Quantum is deterministic rollback; check pricing tiers |
For online play outside a LAN you also need connectivity: Unity's Relay and Lobby services, Steam networking, Epic Online Services, or your own dedicated servers. Check each service's current pricing and terms.
Test yourself
What does a client-to-server RPC represent in a server-authoritative game?
- A command the server must obey
- A request the server validates before changing state
- A replicated variable
- A local-only event
What is required for an NGO 2.x RPC method?
[Command]attribute[Rpc(SendTo.X)]and a method name ending inRpc- It must be static
- A NetworkVariable parameter
Who writes a NetworkVariable<int> with default permissions?
- Any client
- The owner
- The server
- Nobody