unity-multiplayer
Unity 6 multiplayer and networking guide. Use when building multiplayer games, working with Netcode for GameObjects, NetworkManager, NetworkObject, NetworkBehaviour, RPCs (ServerRpc, ClientRpc), NetworkVariables, or Unity multiplayer services (Relay, Lobby). Covers client-server architecture, state synchronization, and scene management. Based on Unity 6.3 LTS documentation.
Nice-Wolf-Studio · 已有静态检查记录
安装与使用
运行命令前先阅读来源与依赖说明。复制命令不会自动安装或执行。
npx skills add Nice-Wolf-Studio/unity-claude-skills --skill unity-multiplayer技能说明
name: unity-multiplayer description: > Unity 6 multiplayer and networking guide. Use when building multiplayer games, working with Netcode for GameObjects, NetworkManager, NetworkObject, NetworkBehaviour, RPCs (ServerRpc, ClientRpc), NetworkVariables, or Unity multiplayer services (Relay, Lobby). Covers client-server architecture, state synchronization, and scene management. Based on Unity 6.3 LTS documentation.
Unity Multiplayer & Networking
Multiplayer Architecture Overview
Unity's multiplayer ecosystem comprises several layers:
| Layer | Package/Service | Purpose |
|---|---|---|
| High-Level | Netcode for GameObjects | GameObject-based networking logic |
| High-Level | Netcode for Entities | DOTS-based networking |
| Low-Level | Unity Transport (com.unity.transport) | UDP/WebSocket communication with optional reliability, ordering, fragmentation |
| Services | Relay | NAT traversal via cloud relay servers |
| Services | Lobby | Matchmaking and session discovery |
| Services | Sessions SDK | Player group management |
| Tools | Multiplayer Play Mode | Simulate up to 4 players in-editor |
| Tools | Multiplayer Tools | Analysis, debugging, testing utilities |
Topology options:
- Client-Server (Dedicated): Server has authority; clients send inputs, server validates
- Client-Server (Listen/Host): One player acts as both server and client
- Distributed Authority: Ownership-based authority distributed among clients
Use the Multiplayer Center (Window > Multiplayer > Multiplayer Center) to get package recommendations based on your game's needs.
Netcode for GameObjects Setup
Installation
Install com.unity.netcode.gameobjects (v2.10+) via Package Manager. This automatically pulls in com.unity.transport.
NetworkManager Configuration
Add a NetworkManager component to a GameObject in your scene. It is the singleton entry point for all networking.
using Unity.Netcode;
public class GameLauncher : MonoBehaviour
{
public void StartAsHost()
{
NetworkManager.Singleton.StartHost();
}
public void StartAsServer()
{
NetworkManager.Singleton.StartServer();
}
public void StartAsClient()
{
NetworkManager.Singleton.StartClient();
}
public void Shutdown()
{
NetworkManager.Singleton.Shutdown();
}
}
Key NetworkManager properties:
IsServer,IsClient,IsHost-- execution contextConnectedClients-- dictionary of connected clientsConnectedClientsIds-- read-only list of client IDsLocalClientId-- local client's IDSceneManager--NetworkSceneManagerinstanceSpawnManager--NetworkSpawnManagerinstanceNetworkConfig-- project network configuration
Key NetworkManager events: OnClientConnectedCallback, OnClientDisconnectCallback, OnConnectionEvent, OnServerStarted/OnServerStopped, OnClientStarted/OnClientStopped, OnTransportFailure
NetworkObject and NetworkBehaviour
NetworkObject
Every networked GameObject needs a NetworkObject component. It provides identity, ownership, and visibility.
Key properties:
NetworkObjectId(ulong) -- unique ID synchronized across networkIsSpawned-- whether spawned on the networkOwnerClientId-- client ID of current ownerIsOwner-- true if local player owns this objectHasAuthority-- true if local instance has authority
Spawning (server-side only):
// Basic spawn
NetworkObject netObj = Instantiate(prefab).GetComponent<NetworkObject>();
netObj.Spawn();
// Spawn with specific owner
netObj.SpawnWithOwnership(clientId);
// Spawn as player object
netObj.SpawnAsPlayerObject(clientId);
// Despawn
netObj.Despawn(destroy: true);
Ownership (server-side only):
netObj.ChangeOwnership(newClientId);
netObj.RemoveOwnership();
Visibility:
netObj.NetworkShow(clientId);
netObj.NetworkHide(clientId);
bool visible = netObj.IsNetworkVisibleTo(clientId);
NetworkBehaviour
All networked scripts inherit from NetworkBehaviour instead of MonoBehaviour.
Lifecycle methods (in order):
OnNetworkPreSpawn(ref NetworkManager)-- before any spawningOnNetworkSpawn()-- after NetworkObject spawns; register handlers hereOnNetworkPostSpawn()-- after all sibling NetworkBehaviours spawnOnNetworkPreDespawn()-- before despawnOnNetworkDespawn()-- on despawn
Ownership callbacks:
OnGainedOwnership()/OnLostOwnership()OnOwnershipChanged(ulong previous, ulong current)-- fires on all clients
using Unity.Netcode;
public class PlayerController : NetworkBehaviour
{
public override void OnNetworkSpawn()
{
if (IsOwner)
{
// Initialize local player controls
EnableInput();
}
}
void Update()
{
if (!IsOwner) return;
// Only the owner processes input
HandleMovement();
}
public override void OnNetworkDespawn()
{
// Cleanup
}
}
Status checks: IsServer, IsClient, IsHost, IsOwner, IsSpawned, IsLocalPlayer, HasAuthority
NetworkVariables
NetworkVariable<T> synchronizes state from server to all clients automatically. Type T must be unmanaged (primitives, unmanaged structs).
public class PlayerHealth : NetworkBehaviour
{
public NetworkVariable<int> Health = new NetworkVariable<int>(
value: 100,
readPerm: NetworkVariableReadPermission.Everyone,
writePerm: NetworkVariableWritePermission.Server
);
public override void OnNetworkSpawn()
{
Health.OnValueChanged += OnHealthChanged;
}
public override void OnNetworkDespawn()
{
Health.OnValueChanged -= OnHealthChanged;
}
private void OnHealthChanged(int oldValue, int newValue)
{
Debug.Log($"Health changed: {oldValue} -> {newValue}");
UpdateHea
阅读完整来源 ↗