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,IsHostare booleans on everyNetworkBehaviourtelling 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