C# for Unity: Coroutines & Multiplayer Networking

Lesson 4 of 7

Intro to Multiplayer: Netcode for GameObjects

Unity's official networking layer is Netcode for GameObjects (NGO). It uses a client-server model: one instance is the server (often also a host, meaning server + local client), everyone else connects as clients.

To make a GameObject network-aware, add a NetworkObject component to its prefab, and give it scripts that inherit from NetworkBehaviour instead of MonoBehaviour.

using Unity.Netcode;

public class PlayerHealth : NetworkBehaviour
{
    public override void OnNetworkSpawn()
    {
        if (IsOwner)
            Debug.Log("This is my player!");
    }
}

Key concepts

  • NetworkManager is the singleton that starts hosting/joining and spawns networked prefabs.
  • NetworkObject identifies a GameObject across the network, only prefabs with one can be spawned with NetworkObject.Spawn().
  • IsServer, IsClient, IsOwner, IsHost are booleans on every NetworkBehaviour telling you which role the current instance is playing.
  • Only the server should spawn, despawn, or authoritatively change networked state, clients request changes, the server decides.
GameObject enemy = Instantiate(enemyPrefab);
enemy.GetComponent<NetworkObject>().Spawn(); // server-only

📝 Netcode Basics Quiz

Passing score: 70%
  1. 1.Which component must a prefab have before it can be spawned across the network?

  2. 2.A networked script inherits from ____ instead of MonoBehaviour.

  3. 3.A host is a server and a local client running at the same time.