Lesson 66 +10 XP

Multiplayer & Netcode

Multiplayer & Netcode

Creating multiplayer games requires synchronizing player positions, states, and game events across a network. Unity's primary solution is Netcode for GameObjects (NGO).

NetworkManager Component

The NetworkManager component is the heart of your multiplayer game. It manages:

  • Connection settings, ports, and protocols.
  • Network Prefabs: The list of player and object prefabs that can spawn across the network.
  • Start and stop states for Host, Server, and Client.
  • Host: Acts as both a server and a client.
  • Client: Connects to the host/server to play.
  • Server: Handles game authority without rendering visuals.

NetworkBehaviour & NetworkVariable

To synchronize variables over the network, inherit from NetworkBehaviour instead of MonoBehaviour:

using Unity.Netcode;

public class PlayerHealth : NetworkBehaviour
{
    // Synchronizes the health value across all clients automatically
    public NetworkVariable<int> health = new NetworkVariable<int>(100);
}

Remote Procedure Calls (RPCs)

RPCs send instruction calls across the network:

  • [ServerRpc]: Called by a client, executed on the server. Useful for player actions (e.g. shooting).
  • [ClientRpc]: Called by the server, executed on all connected clients. Useful for game announcements or effects.

TL;DR

  • Netcode for GameObjects is Unity's official multiplayer solution.
  • The NetworkManager component manages network connections and prefabs.
  • Inherit from NetworkBehaviour for networked scripts.
  • Use NetworkVariable for data sync, and RPCs ([ServerRpc] / [ClientRpc]) to send commands.