TExcelTAD
Home › Multiplayer Game Networking › Unity Netcode for GameObjects

Unity Netcode for GameObjects

Netcode for GameObjects (NGO, package com.unity.netcode.gameobjects) is Unity's own high-level networking library for ordinary GameObject projects. Version 2.x targets Unity 6. It gives you the pieces this course built by hand: a connection manager, spawned networked objects, replicated variables, remote procedure calls, and a transport underneath (Unity Transport, UDP with its own reliability layer). This lesson maps those pieces onto the ideas you already know, and runs a small model of what NGO does with a replicated variable.

Note: For DOTS/ECS projects Unity has a separate package, Netcode for Entities, with built-in client prediction and snapshot interpolation. NGO is the usual choice for small and mid-sized co-op and session games. See the Unity course for the engine basics.

The building blocks

NGO piece What it is Course idea
NetworkManager one per game: starts a server, host (server + local player) or client, holds the transport and prefab list connection handling (Connections, Timeouts & Reconnects)
UnityTransport the default transport component UDP + reliability (Reliability over UDP)
NetworkObject a GameObject the network knows about; has an owner client entity ids, ownership
NetworkBehaviour a MonoBehaviour that can use network variables and RPCs your replicated component
NetworkVariable<T> a value the authority writes and everyone reads state sync (State Sync & Snapshots)
[Rpc(SendTo.Server)] a method call sent to another machine sending inputs and events
NetworkTransform replicates position/rotation/scale, with interpolation Snapshot Interpolation

Starting a session is one call on the manager, usually from a menu button:

csharp
using Unity.Netcode;
using UnityEngine;

public class Menu : MonoBehaviour
{
    public void Host()   => NetworkManager.Singleton.StartHost();    // server + a local player
    public void Join()   => NetworkManager.Singleton.StartClient();  // address/port come from UnityTransport
    public void Server() => NetworkManager.Singleton.StartServer();  // dedicated server build
}

A player component

The pattern this course keeps repeating (send inputs, let the server decide, replicate the result) looks like this in NGO:

csharp
using Unity.Netcode;
using UnityEngine;

public class PlayerNet : NetworkBehaviour
{
    // Server writes, everyone reads: these are the defaults, spelled out here.
    public NetworkVariable<int> Health = new NetworkVariable<int>(100,
        NetworkVariableReadPermission.Everyone,
        NetworkVariableWritePermission.Server);

    public override void OnNetworkSpawn()
    {
        Health.OnValueChanged += OnHealthChanged;   // subscribe here, not in Awake/Start
    }

    public override void OnNetworkDespawn()
    {
        Health.OnValueChanged -= OnHealthChanged;
    }

    void OnHealthChanged(int previous, int current)
    {
        Debug.Log(
quot;health {previous} -> {current}"); // update the HUD, play a hit effect } void Update() { if (!IsOwner) return; // only the owning client reads its keyboard Vector2 move = ReadMoveInput(); if (move != Vector2.zero) MoveRpc(move); } // Runs on the server. The method name must end in "Rpc". [Rpc(SendTo.Server)] void MoveRpc(Vector2 input, RpcParams rpcParams = default) { Vector2 clamped = Vector2.ClampMagnitude(input, 1f); // never trust the client transform.position += (Vector3)(clamped * 5f * Time.deltaTime); } [Rpc(SendTo.Server)] void FireRpc(RpcParams rpcParams = default) { ulong sender = rpcParams.Receive.SenderClientId; // who really sent it // ... cooldown check, spawn a projectile NetworkObject ... } Vector2 ReadMoveInput() => Vector2.zero; // Input System code goes here }

Points worth remembering:

  • Universal [Rpc] attribute. Since NGO 1.8 one attribute covers every direction: SendTo.Server, SendTo.Owner, SendTo.NotOwner, SendTo.Everyone, SendTo.ClientsAndHost, SendTo.NotMe, SendTo.SpecifiedInParams and more. The older [ServerRpc] / [ClientRpc] attributes still compile, but Unity's docs mark them as legacy. New code should use [Rpc].
  • RpcParams last. An optional last parameter of type RpcParams isn't serialized. On the receiving side it tells you the sender (rpcParams.Receive.SenderClientId). Use that, never a client id passed as an argument, which a cheater can fake.
  • RequireOwnership. [Rpc(SendTo.Server, RequireOwnership = true)] refuses calls from clients that don't own the object. The default is false, so think about who may call each RPC.
  • NetworkVariable permissions. By default the server writes and everyone reads. NetworkVariableWritePermission.Owner lets the owning client write (useful for cosmetic state, risky for anything that matters).
  • Supported types. Unmanaged primitives, Unity value types (Vector3, Quaternion, Color), enums, FixedString… types instead of string, and your own structs implementing INetworkSerializable. If you change the contents of a collection held in a NetworkVariable, call CheckDirtyState() so NGO notices.

A model of a NetworkVariable

What does NGO do with Health.Value = 75? It checks the write permission, compares with the old value, marks the variable dirty, and at the end of the network tick serializes only dirty variables into one message for each client. Each client applies the new value and raises OnValueChanged(previous, current). Here is that loop in plain TypeScript, with client 1 owning the player:

ts · try it yourself
type ClientId = number;
const SERVER: ClientId = 0;

class NetVar<T> {
  dirty = false;
  listeners: ((prev: T, cur: T) => void)[] = [];
  constructor(public name: string, private value: T, readonly writePerm: 'Server' | 'Owner') {}
  get value_(): T { return this.value; }
  write(v: T, writer: ClientId, owner: ClientId): string {
    const ok = this.writePerm === 'Server' ? writer === SERVER : writer === owner;
    if (!ok) return `rejected: client ${writer} may not write ${this.name} (${this.writePerm} write)`;
    if (v === this.value) return `${this.name} unchanged: nothing to send`;
    this.value = v;
    this.dirty = true;
    return `${this.name} = ${v} (dirty)`;
  }
  apply(v: T) {                       // on a client, when the update arrives
    const prev = this.value;
    this.value = v;
    this.listeners.forEach((f) => f(prev, v));
  }
}

const owner: ClientId = 1;
type Val = number | string;
const makeVars = () => [new NetVar<Val>('Health', 100, 'Server'), new NetVar<Val>('Emote', 'none', 'Owner')];
const [health, emote] = makeVars();                 // the server's copies
const replica = makeVars();                          // client 1's copies, same order = same ids
replica[0].listeners.push((p, c) => console.log(`  client 1 OnValueChanged: Health ${p} -> ${c}`));

function endOfTick(tick: number) {
  const ids = [health, emote].map((v, id) => (v.dirty ? id : -1)).filter((id) => id >= 0);
  const bytes = ids.length === 0 ? 0 : 4 + ids.length * 6;              // header + (id, value) per variable
  console.log(`tick ${tick}: send ${ids.map((id) => [health, emote][id].name).join(', ') || 'nothing'} (${bytes} bytes)`);
  for (const id of ids) {
    const v = [health, emote][id];
    replica[id].apply(v.value_);
    v.dirty = false;
  }
}

console.log(health.write(75, SERVER, owner));
console.log(health.write(60, SERVER, owner));   // two writes in one tick: only the last is sent
endOfTick(1);
console.log(health.write(999, 1, owner));      // a client tries to heal itself
console.log(health.write(60, SERVER, owner));
endOfTick(2);
console.log(emote.write('wave', 1, owner));    // owner-writable cosmetic state
endOfTick(3);
Health = 75 (dirty)
Health = 60 (dirty)
tick 1: send Health (10 bytes)
  client 1 OnValueChanged: Health 100 -> 60
rejected: client 1 may not write Health (Server write)
Health unchanged: nothing to send
tick 2: send nothing (0 bytes)
Emote = wave (dirty)
tick 3: send Emote (10 bytes)

Three things to notice: two writes in the same tick cost one update (only the latest value travels), writing the same value sends nothing, and the permission check runs on the machine that owns the truth. In NGO an owner-writable variable is written on the owner's client and synced from there; the model simply shows that the server accepts it.

Hosting, relay and lobbies

NGO only moves game traffic. For players behind home routers to find and reach each other you add services: Unity's Relay (traffic through Unity's servers, no port forwarding) and Lobby, or Multiplay-style dedicated hosting and third-party hosts. Those are covered with the other backend services in Steamworks, EOS, Nakama & PlayFab and Dedicated Servers & Hosting. For testing under lag inside the editor, see Network Conditioners, Wireshark & Profilers.

Tip: NGO has no built-in client prediction for GameObjects. If your game needs responsive movement at 100+ ms, you write prediction and reconciliation yourself on top of RPCs (the technique from Client-Side Prediction), or pick a library that ships it (Netcode for Entities, FishNet, Photon Fusion).

Test yourself

What is the current recommended way to declare a client-to-server call in Netcode for GameObjects?

  1. [ServerRpc] on a method ending in ServerRpc
  2. [Rpc(SendTo.Server)] on a method whose name ends in Rpc
  3. [Command] on a method starting with Cmd
  4. UFUNCTION(Server, Reliable)

Inside a server RPC, how should you find out which client called it?

  1. Pass the client id as an argument
  2. Read rpcParams.Receive.SenderClientId from an RpcParams parameter
  3. Use OwnerClientId of any object
  4. You can't

The server sets Health.Value to 75 and then to 60 in the same tick. What do clients receive?

  1. Two updates, 75 then 60
  2. One update with 60
  3. Nothing until the next spawn
  4. An RPC per write