Logotipo de Unity Multiplayer

Unity Multiplayer

Organización
Nice-Wolf-Studio
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.

Descripción general

EditorNice-Wolf-Studio
Repositoriounity-claude-skills
Nombre de la habilidadunity-multiplayer
Estrellas
40
Forks
5
Archivos incluidos
2
LicenciaMIT
Enlaces
  • Instrucciones en Markdown

    Un archivo SKILL.md que el modelo carga cuando lo necesita, de modo que solo consume tokens cuando una petición es realmente relevante.

  • Funciona con cualquier LLM

    Las habilidades de IA están en Markdown, no en código específico de un proveedor, por lo que funcionan con GPT, Claude, Gemini, Grok o un modelo local.

  • 2 archivos incluidos

    Scripts, plantillas y referencias que el modelo puede leer mientras trabaja. Los archivos son de solo lectura y nunca se ejecutan.

  • Código abierto

    Publicada por Nice-Wolf-Studio en GitHub. Revisa el contenido original antes de instalarla.

Instalación

Instala la habilidad de IA Unity Multiplayer en TypingMind para usarla con cualquier LLM, o añádela a otro agente que lea SKILL.md.

1

Instalar en TypingMind

TypingMind instala una habilidad directamente desde su carpeta de GitHub: lee SKILL.md, empaqueta los archivos de recursos y guarda el resultado localmente.

  1. Abre la aplicación y ve a Plugins → Habilidades.
  2. Elige «Instalar desde GitHub».
  3. Pega la URL de la carpeta de la habilidad que se muestra a continuación y confirma.
    https://github.com/Nice-Wolf-Studio/unity-claude-skills/tree/main/skills/unity-multiplayer
  4. Activa la habilidad en cada chat en el que quieras tenerla disponible.
Plugins → Habilidades → Añadir habilidad → Desde URL de GitHub; después, pega la URL de la carpeta y pulsa Continuar.
2

Instalar en otro agente

Cualquier agente que lea el formato Agent Skills puede usar esta habilidad: copia la carpeta en el directorio de habilidades de ese agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/Nice-Wolf-Studio/unity-claude-skills.git /tmp/unity-claude-skills
mkdir -p .claude/skills
cp -r /tmp/unity-claude-skills/skills/unity-multiplayer .claude/skills/unity-multiplayer
Reinicia Claude Code después de copiarla para que detecte la nueva habilidad.

Úsala en TypingMind

Activa Unity Multiplayer en cualquier chat de TypingMind y el modelo se encargará del resto. Su nombre y descripción se incluyen en el prompt del sistema y, en cuanto una petición es relevante, el modelo carga las instrucciones completas por sí solo. No tienes que invocarla manualmente y no consume tokens hasta que se utiliza.

El modelo carga Unity Multiplayer automáticamente en cuanto una petición es relevante para esa habilidad.

Funciona con cualquier modelo de IA

Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que Unity Multiplayer no está vinculada al modelo para el que se creó. Instálala una sola vez en TypingMind y úsala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modelo local que ejecutes tú, todo con tus propias claves API.

  • Se carga solo cuando se necesita

    El prompt del sistema solo incluye el nombre y la descripción. Las instrucciones se cargan con la primera petición relevante, por lo que una habilidad que no se usa no supone ningún coste.

  • Cambia de modelo durante el chat

    Como la habilidad contiene instrucciones y no código, cambiar de modelo no impide que funcione: el nuevo modelo lee el mismo archivo SKILL.md.

Instrucciones de la habilidad

Este es el contenido de SKILL.md que carga el modelo. Léelo antes de instalar la habilidad: contiene instrucciones que tu modelo seguirá.

Unity Multiplayer & Networking

Multiplayer Architecture Overview

Unity's multiplayer ecosystem comprises several layers:

LayerPackage/ServicePurpose
High-LevelNetcode for GameObjectsGameObject-based networking logic
High-LevelNetcode for EntitiesDOTS-based networking
Low-LevelUnity Transport (com.unity.transport)UDP/WebSocket communication with optional reliability, ordering, fragmentation
ServicesRelayNAT traversal via cloud relay servers
ServicesLobbyMatchmaking and session discovery
ServicesSessions SDKPlayer group management
ToolsMultiplayer Play ModeSimulate up to 4 players in-editor
ToolsMultiplayer ToolsAnalysis, 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.

csharp
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 context
  • ConnectedClients -- dictionary of connected clients
  • ConnectedClientsIds -- read-only list of client IDs
  • LocalClientId -- local client's ID
  • SceneManager -- NetworkSceneManager instance
  • SpawnManager -- NetworkSpawnManager instance
  • NetworkConfig -- 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 network
  • IsSpawned -- whether spawned on the network
  • OwnerClientId -- client ID of current owner
  • IsOwner -- true if local player owns this object
  • HasAuthority -- true if local instance has authority

Spawning (server-side only):

csharp
// 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):

csharp
netObj.ChangeOwnership(newClientId);
netObj.RemoveOwnership();

Visibility:

csharp
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):

  1. OnNetworkPreSpawn(ref NetworkManager) -- before any spawning
  2. OnNetworkSpawn() -- after NetworkObject spawns; register handlers here
  3. OnNetworkPostSpawn() -- after all sibling NetworkBehaviours spawn
  4. OnNetworkPreDespawn() -- before despawn
  5. OnNetworkDespawn() -- on despawn

Ownership callbacks:

  • OnGainedOwnership() / OnLostOwnership()
  • OnOwnershipChanged(ulong previous, ulong current) -- fires on all clients
csharp
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).

csharp
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}");
        UpdateHealthUI(newValue);
    }

    // Server-side only (due to WritePerm.Server)
    public void TakeDamage(int amount)
    {
        if (!IsServer) return;
        Health.Value -= amount;
    }
}

Write permissions:

  • NetworkVariableWritePermission.Server (default) -- only server can write
  • NetworkVariableWritePermission.Owner -- only owner can write

NetworkList -- synchronized list (T must be unmanaged + IEquatable<T>):

csharp
public class Inventory : NetworkBehaviour
{
    public NetworkList<int> Items;

    void Awake()
    {
        Items = new NetworkList<int>();
    }

    public override void OnNetworkSpawn()
    {
        Items.OnListChanged += OnItemsChanged;
    }

    private void OnItemsChanged(NetworkListEvent<int> changeEvent)
    {
        Debug.Log($"List changed: {changeEvent.Type}");
    }
}

RPCs (ServerRpc, ClientRpc)

RPCs are remote procedure calls between server and clients. Methods must be in a NetworkBehaviour and use the [Rpc] attribute with a SendTo target.

Unified Rpc Attribute (v2.x)

csharp
public class CombatSystem : NetworkBehaviour
{
    // Server executes this when any client calls it
    [Rpc(SendTo.Server)]
    void AttackRpc(int targetId, RpcParams rpcParams = default)
    {
        ulong senderId = rpcParams.Receive.SenderClientId;
        ProcessAttack(senderId, targetId);
    }

    // All clients (and host) execute this
    [Rpc(SendTo.ClientsAndHost)]
    void ShowDamageEffectRpc(Vector3 position, int damage)
    {
        SpawnDamagePopup(position, damage);
    }

    // Only the owner executes this
    [Rpc(SendTo.Owner)]
    void NotifyOwnerRpc(string message)
    {
        Debug.Log(message);
    }

    // Everyone including sender
    [Rpc(SendTo.Everyone)]
    void PlaySoundRpc(int soundId)
    {
        AudioManager.Play(soundId);
    }
}

SendTo Targets

TargetDescription
ServerExecutes on server; locally if called on server
NotServerAll clients except server (excludes host)
OwnerObject's owner only
NotOwnerEveryone except owner
AuthorityServer in client-server; owner in distributed authority
NotAuthorityAll non-authority instances
ClientsAndHostAll clients including host
EveryoneAll instances on the observer list
MeLocal execution only
NotMeEveryone except sender
SpecifiedInParamsTarget set at runtime via RpcSendParams

Legacy Attributes (still supported)

csharp
[ServerRpc]
void RequestSpawnServerRpc(ServerRpcParams rpcParams = default)
{
    // Runs on server; only owner can call by default
}

[ClientRpc]
void UpdateUIClientRpc(int score)
{
    // Runs on all clients
}

Connection Approval

Use ConnectionApprovalCallback on NetworkManager to validate connecting clients.

csharp
// Server-side: register approval callback
NetworkManager.Singleton.ConnectionApprovalCallback = (request, response) =>
{
    string password = System.Text.Encoding.UTF8.GetString(request.Payload);
    response.Approved = (password == "secret");
    response.CreatePlayerObject = response.Approved;
    // Optionally set: response.PlayerPrefabHash, response.Position, response.Rotation
    if (!response.Approved) response.Reason = "Invalid password";
    response.Pending = false; // Signal decision is made
};

// Client-side: set payload before connecting
NetworkManager.Singleton.NetworkConfig.ConnectionData =
    System.Text.Encoding.UTF8.GetBytes("secret");
NetworkManager.Singleton.StartClient();

Scene Management

NetworkSceneManager (accessed via NetworkManager.Singleton.SceneManager) handles synchronized scene loading.

csharp
public class GameSceneManager : NetworkBehaviour
{
    public void LoadGameScene()
    {
        if (!IsServer) return;
        // Server-only: loads scene on all clients
        NetworkManager.Singleton.SceneManager.LoadScene("GameScene", LoadSceneMode.Single);
    }

    public void LoadAdditiveScene()
    {
        if (!IsServer) return;
        NetworkManager.Singleton.SceneManager.LoadScene("Arena", LoadSceneMode.Additive);
    }

    public override void OnNetworkSpawn()
    {
        NetworkManager.Singleton.SceneManager.OnSceneEvent += OnSceneEvent;
    }

    void OnSceneEvent(SceneEvent sceneEvent)
    {
        switch (sceneEvent.SceneEventType)
        {
            case SceneEventType.LoadComplete:
                Debug.Log($"Client {sceneEvent.ClientId} loaded {sceneEvent.SceneName}");
                break;
            case SceneEventType.LoadEventCompleted:
                Debug.Log($"All clients loaded {sceneEvent.SceneName}");
                break;
            case SceneEventType.SynchronizeComplete:
                Debug.Log($"Client {sceneEvent.ClientId} fully synchronized");
                break;
        }
    }
}

Scene event types: OnLoad, OnUnload, OnSynchronize, OnLoadComplete, OnUnloadComplete, OnLoadEventCompleted, OnUnloadEventCompleted, OnSynchronizeComplete

Important: Do NOT start new scene events within scene event callbacks.

Unity Multiplayer Services (Relay, Lobby)

Full integration examples in references/transport-layer.md

Unity Relay

Relay provides NAT punchthrough via cloud relay servers (no port forwarding needed). Requires UGS authentication.

Host flow: Create allocation, get join code, configure transport, start host. Client flow: Join allocation with code, configure transport, start client.

csharp
// Host: create relay and start
Allocation allocation = await RelayService.Instance.CreateAllocationAsync(maxPlayers);
string joinCode = await RelayService.Instance.GetJoinCodeAsync(allocation.AllocationId);
transport.SetRelayServerData(allocation.ToRelayServerData("dtls")); // "dtls" = encrypted UDP
NetworkManager.Singleton.StartHost();

// Client: join relay and connect
JoinAllocation join = await RelayService.Instance.JoinAllocationAsync(joinCode);
transport.SetRelayServerData(join.ToRelayServerData("dtls"));
NetworkManager.Singleton.StartClient();

Unity Lobby

Lobby provides session discovery and matchmaking. Store the Relay join code in lobby data.

csharp
// Create lobby with relay join code
_lobby = await LobbyService.Instance.CreateLobbyAsync(name, maxPlayers, new CreateLobbyOptions {
    Data = new Dictionary<string, DataObject> {
        { "JoinCode", new DataObject(DataObject.VisibilityOptions.Member, relayJoinCode) }
    }
});

// Query available lobbies
QueryResponse response = await Lobbies.Instance.QueryLobbiesAsync(new QueryLobbiesOptions {
    Filters = new List<QueryFilter> {
        new QueryFilter(QueryFilter.FieldOptions.AvailableSlots, "0", QueryFilter.OpOptions.GT)
    }
});

// Join and extract relay code
Lobby lobby = await LobbyService.Instance.JoinLobbyByIdAsync(lobbyId);
string joinCode = lobby.Data["JoinCode"].Value;

// IMPORTANT: Send heartbeats every 15s or lobby expires
await LobbyService.Instance.SendHeartbeatPingAsync(lobby.Id);

Common Patterns

Player Spawning with Custom Prefab (Server-Side)

csharp
// In a NetworkBehaviour on the server:
NetworkManager.Singleton.OnClientConnectedCallback += (ulong clientId) => {
    GameObject player = Instantiate(playerPrefab);
    player.GetComponent<NetworkObject>().SpawnAsPlayerObject(clientId);
};

Owner-Authoritative Movement

csharp
public class PlayerMovement : NetworkBehaviour
{
    public NetworkVariable<Vector3> Position = new(writePerm: NetworkVariableWritePermission.Owner);
    void Update()
    {
        if (!IsOwner) return;
        // Note: Uses legacy Input for brevity. See unity-input for the new Input System.
        Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
        transform.position += move * Time.deltaTime * 5f;
        Position.Value = transform.position;
    }
}

Server-Authoritative with Input RPCs

csharp
public class ServerAuthMovement : NetworkBehaviour
{
    [Rpc(SendTo.Server)]
    void MoveRpc(Vector3 input) { transform.position += input * Time.deltaTime * 5f; }
    void Update()
    {
        if (!IsOwner) return;
        MoveRpc(new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"))); // legacy Input; see unity-input
    }
}

Anti-Patterns

  1. Writing to NetworkVariable without authority -- Only the server (or owner with WritePerm.Owner) can write. Client writes are silently ignored.

  2. Forgetting IsOwner checks in Update -- Without owner checks, all clients run input logic, causing conflicting state.

  3. Using Instantiate without Spawn -- Objects created with Instantiate alone are local-only. Always call Spawn() on the NetworkObject for network visibility.

  4. Spawning from client code -- Only the server can spawn NetworkObjects. Clients must send an RPC to request spawning.

  5. Heavy data in RPCs instead of NetworkVariables -- RPCs are fire-and-forget; late joiners miss them. Use NetworkVariables for persistent state.

  6. Not unsubscribing from OnValueChanged -- Subscribe in OnNetworkSpawn, unsubscribe in OnNetworkDespawn to prevent leaks.

  7. Starting scene events inside scene event callbacks -- NetworkSceneManager forbids this; causes undefined behavior.

  8. Not sending Lobby heartbeats -- Lobbies expire without periodic SendHeartbeatPingAsync calls (every 15-30 seconds).

  9. Using NetworkVariable for frequent small updates -- For high-frequency data (position), prefer NetworkTransform or custom serialization.

  10. Calling RPCs before OnNetworkSpawn -- RPCs require the NetworkObject to be spawned. Defer to OnNetworkSpawn.

Key API Quick Reference

ClassKey Members
NetworkManagerStartHost(), StartServer(), StartClient(), Shutdown(), Singleton, ConnectedClients, LocalClientId, SceneManager, ConnectionApprovalCallback
NetworkObjectSpawn(), SpawnWithOwnership(), SpawnAsPlayerObject(), Despawn(), ChangeOwnership(), NetworkShow(), NetworkHide(), NetworkObjectId, OwnerClientId, IsOwner, HasAuthority
NetworkBehaviourOnNetworkSpawn(), OnNetworkDespawn(), OnGainedOwnership(), OnLostOwnership(), IsServer, IsClient, IsHost, IsOwner, IsSpawned, HasAuthority, RpcTarget
NetworkVariable<T>.Value, OnValueChanged, ReadPerm, WritePerm, CheckDirtyState()
NetworkList<T>Add(), Remove(), Insert(), Clear(), Count, OnListChanged
NetworkSceneManagerLoadScene(), UnloadScene(), OnSceneEvent
[Rpc(SendTo.X)]Server, Owner, NotOwner, ClientsAndHost, Everyone, NotMe, Authority, SpecifiedInParams

Related Skills

  • unity-foundations -- Core Unity concepts, GameObjects, components, scene hierarchy
  • unity-scripting -- C# scripting, MonoBehaviour lifecycle, coroutines
  • unity-physics -- Physics systems; use NetworkRigidbody for synced physics

Additional Resources

Archivos incluidos

El modelo los lee según los necesita mientras la habilidad está cargada. Se ofrecen como archivos de lectura y nunca se ejecutan.

Preguntas frecuentes

¿Qué hace la habilidad de IA 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.

¿Por qué usar Unity Multiplayer en TypingMind?

Porque la instalas una vez y la usas con cualquier modelo. Unity Multiplayer está escrita en Markdown, no en código específico de un proveedor, por lo que la misma habilidad funciona con GPT-5, Claude, Gemini, Grok o un modelo local, y puedes cambiar de modelo en mitad del chat sin que deje de funcionar. TypingMind utiliza tus propias claves API, de modo que pagas directamente a los proveedores en lugar de pagar una suscripción por puesto, y tus habilidades y chats permanecen en tu propio almacenamiento.

¿Cómo instalo Unity Multiplayer en TypingMind?

Abre Plugins → Habilidades → Instalar desde GitHub en TypingMind y pega https://github.com/Nice-Wolf-Studio/unity-claude-skills/tree/main/skills/unity-multiplayer. TypingMind lee su archivo SKILL.md, empaqueta sus archivos y la instala como una habilidad que puedes activar en cada chat.

¿Qué modelos de IA pueden usar Unity Multiplayer?

Cualquier modelo que conectes en TypingMind. Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que GPT, Claude, Gemini, Grok y los modelos locales pueden cargar esta habilidad cuando una solicitud se corresponda con ella.

¿Con cuántos modelos de IA puedo usar Unity Multiplayer?

Con tantos como quieras. Siempre que un modelo admita habilidades, puedes usar Unity Multiplayer con él: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama y muchos más, todos en TypingMind con tus propias claves API.

¿Es gratuita la habilidad de IA Unity Multiplayer?

Sí. Nice-Wolf-Studio la ha publicado en GitHub bajo la licencia MIT. Solo pagas a tu proveedor de IA por los tokens que utilizas.

¿Qué son las habilidades de IA?

Una habilidad de IA es un conjunto de instrucciones reutilizables que enseña a un modelo de IA a realizar una tarea concreta. Sigue el formato abierto Agent Skills: un archivo SKILL.md con un nombre y una descripción, además de los scripts, plantillas o archivos de referencia que pueda necesitar el modelo. El modelo solo lee las instrucciones cuando tu solicitud se corresponde con la habilidad, por lo que una habilidad instalada no supone ningún coste hasta que se utiliza.

¿En qué se diferencian las habilidades de IA de los plugins o los servidores MCP?

Un plugin o un servidor MCP proporciona al modelo nuevas herramientas que puede invocar: código que se ejecuta en algún lugar y devuelve un resultado. En cambio, una habilidad de IA aporta conocimientos y procedimientos al modelo: cómo abordar una tarea, qué pasos seguir y qué se considera un buen resultado. Las habilidades son instrucciones en Markdown, por lo que no necesitan servidor, clave API ni entorno de ejecución, y funcionan con cualquier modelo.

Ver todos

Crea ya tu propio espacio de trabajo IA

Suscríbete a nuestro boletín para recibir avisos sobre nuevas funciones y próximos sorteos 👇