> ## Documentation Index
> Fetch the complete documentation index at: https://devdocs.xbox.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Inicio rápido del complemento de Unity de Multiplayer

> Instale el complemento PlayFab Multiplayer para Unity y realice sus primeras llamadas a las API de Lobby y Matchmaking desde un proyecto de Unity, incluidas las consideraciones de configuración del GDK.

# Inicio rápido: complemento PlayFab Multiplayer para Unity

Comience a usar el complemento PlayFab Multiplayer para Unity. Siga los pasos que se indican a continuación para instalar el paquete y probar código de ejemplo para una tarea básica.

Este inicio rápido le ayuda a realizar sus primeras llamadas a la API con el SDK de PlayFab Multiplayer para Unity. Antes de continuar, asegúrese de completar [Inicio rápido: biblioteca cliente de PlayFab para C# en Unity](/services/playfab/sdks/unity3d/quickstart), lo que garantiza que tiene una cuenta de PlayFab y que está familiarizado con el inicio de sesión en PlayFab desde su juego y con el Game Manager de PlayFab.

<Note>
  Si tiene previsto usar este complemento para desarrollar juegos basados en el Microsoft Game Development Kit (GDK), debe adquirir e instalar el GDK por separado. Consulte también los detalles sobre el complemento de Unity para Game Core en consolas XBOX.
</Note>

## Requisitos

* Una [cuenta de desarrollador de PlayFab](https://developer.playfab.com).

* Una copia instalada del editor de Unity. Para instalar Unity para uso personal a través de Unity Hub, o Unity+ para uso profesional, consulte [Download Unity](https://unity3d.com/get-unity/download). Compruebe la compatibilidad con Unity en la documentación de su plataforma específica si es necesario. La versión mínima compatible de Unity es Unity 2017 LTS.

* Un proyecto de Unity: puede ser cualquiera de los siguientes:

  * Un proyecto totalmente nuevo: para obtener más información, consulte [Iniciar Unity por primera vez](/services/playfab/sdks/unity3d/quickstart).
  * Un proyecto de tutorial guiado. Para obtener más información, consulte [Getting Started with Unity](https://learn.unity.com/).
  * Un proyecto existente.

* El SDK "core" de PlayFab para Unity3D (también incluido en el complemento de Unity de Multiplayer). Para obtener información sobre la instalación del SDK de Unity3D, consulte la sección "Descargar e instalar el SDK de PlayFab" de [Inicio rápido: biblioteca cliente de PlayFab para C# en Unity](/services/playfab/sdks/unity3d/quickstart#download-and-install-playfab-sdk).

## Descargar e instalar el complemento PlayFab Multiplayer para Unity

Siga los pasos para descargar e instalar el complemento PlayFab Multiplayer para Unity.

1. Descargue el paquete de recursos del [complemento de Unity de Multiplayer](https://github.com/PlayFab/PlayFabMultiplayerUnity) de PlayFab (use un punto de distribución según su plataforma).
2. **¡Importante!** Consulte la información del archivo README publicado con el complemento. Está adaptado a cada versión concreta y puede incluir instrucciones importantes específicas de su plataforma.
3. Abra su proyecto de Unity.
4. Vaya a la ubicación donde guardó el archivo .unitypackage y haga doble clic en él para abrir el cuadro de diálogo de importación.
5. Para importar el complemento PlayFab Multiplayer para Unity en su proyecto, seleccione **Import**.

Nota: es posible que necesite instalar una versión más reciente del SDK "core" de PlayFab para Unity si es necesario.

## Configurar la escena

Esta parte de la guía muestra cómo agregar el `PlayfabMultiplayerEventProcessor` a la escena para poder llamar a las API de PlayFab Multiplayer desde Unity.

Antes de poder usar la API de Multiplayer, **debe tener un jugador de PlayFab con la sesión iniciada**. Para obtener información sobre cómo iniciar la sesión de un jugador, consulte [Realizar la primera llamada a la API en Inicio rápido: biblioteca cliente de PlayFab para C# en Unity](/services/playfab/sdks/unity3d/quickstart#making-your-first-api-call).

1. En el editor de Unity, en la ventana Project, vaya a **Assets > PlayFabMultiplayerSDK > Prefabs**.

2. Desde la carpeta Prefabs, arrastre y suelte **PlayfabMultiplayerEventProcessor** en su escena en la ventana **Hierarchy**.

3. Cree un Game Object vacío en su escena llamado "HelloMultiplayerLogic".

4. Seleccione el Game Object HelloMultiplayerLogic para abrir el **Inspector**.

5. Seleccione **Add Component**.

6. Escriba "HelloMultiplayerLogic" y presione Entrar para mostrar el menú de nuevo script.

7. Presione Entrar de nuevo para crear el nuevo script, HelloMultiplayerLogic.cs.

8. Busque el script en la ventana **Project** y haga doble clic en él para editarlo.

9. Agregue la siguiente instrucción using a su script:

   ```csharp theme={null}
   using PlayFab;
   using PlayFab.Multiplayer;
   using PlayFab.ClientModels;
   ```

10. Agregue el siguiente código en el método Start para iniciar sesión en PlayFab.

    ```csharp theme={null}
    // Log into playfab
    var request = new LoginWithCustomIDRequest { CustomId = UnityEngine.Random.value.ToString(), CreateAccount = true };
    PlayFabClientAPI.LoginWithCustomID(request, OnLoginSuccess, OnLoginFailure);
    ```

11. Agregue los siguientes métodos a la clase.

    ```csharp theme={null}
    private void OnLoginSuccess(LoginResult result)
    {
    }

    private void OnLoginFailure(PlayFabError error)
    {
    }
    ```

<Note>
  Es posible que reciba los siguientes errores: `C \# Error CS0227 Unsafe code may only appear if compiling with /unsafe The plugin requires unsafe code because it interops with a native DLL. Mismatch between the processor architecture of the project being built "MSIL" and the processor architecture of the reference "XGamingRuntime", "AMD64".`
</Note>

El Microsoft GDK y Windows solo admiten x64.

Para resolver estos problemas:

1. En el editor de Unity, seleccione **File > Build Settings.**
2. Seleccione su plataforma. Después, en la lista desplegable **Architecture**, seleccione x86\_64 o x64.
3. Seleccione **Player Settings.**
4. En el panel derecho, seleccione Other Setting.
5. Busque la opción **Allow unsafe Code** y selecciónela.
6. Cierre las ventanas **Build Settings** y **Project Settings**.

## Crear un lobby y unirse a él

Esta parte de la guía muestra cómo crear un lobby y unirse a él.

1. Abra el script HelloMultiplayerLogic.cs. En el método `OnLoginSuccess`, agregue el siguiente código para crear un lobby y unirse a él:

   ```csharp theme={null}
   string entityId = ...; // PlayFab user's entity Id
   string entityType = ...; // PlayFab user's entity type

   PlayFabMultiplayer.OnLobbyCreateAndJoinCompleted += this.PlayFabMultiplayer_OnLobbyCreateAndJoinCompleted;
   PlayFabMultiplayer.OnLobbyDisconnected += this.PlayFabMultiplayer_OnLobbyDisconnected;

   var createConfig = new LobbyCreateConfiguration()
   {
       MaxMemberCount = 10,
       OwnerMigrationPolicy = LobbyOwnerMigrationPolicy.Automatic,
       AccessPolicy = LobbyAccessPolicy.Public
   };

   createConfig.LobbyProperties["Prop1"] = "Value1";
   createConfig.LobbyProperties["Prop2"] = "Value2";

   var joinConfig = new LobbyJoinConfiguration();
   joinConfig.MemberProperties["MemberProp1"] = "MemberValue1";
   joinConfig.MemberProperties["MemberProp2"] = "MemberValue2";

   PlayFabMultiplayer.CreateAndJoinLobby(
       new PFEntityKey(
           entityId,
           entityType),
       createConfig,
       joinConfig);
   ```

2. Para definir el controlador de eventos OnLobbyCreateAndJoinCompleted, agregue el siguiente código a la clase:

   ```csharp theme={null}
   private void PlayFabMultiplayer_OnLobbyCreateAndJoinCompleted(Lobby lobby, int result)
   {
       if (LobbyError.SUCCEEDED(result))
       {
           // Lobby was successfully created
           Debug.Log(lobby.ConnectionString);
       }
       else
       {
           // Error creating a lobby
           Debug.Log("Error creating a lobby");
       }
   }
   ```

3. Para definir el controlador de eventos OnLobbyDisconnected, agregue el siguiente código a la clase:

   ```csharp theme={null}
   private void PlayFabMultiplayer_OnLobbyDisconnected(Lobby lobby)
   {
       // Disconnected from lobby
       Debug.Log("Disconnected from lobby!");
   }
   ```

4. Guarde y seleccione Play en el editor de Unity. La cadena de conexión del lobby se muestra en la ventana Console.

## Unirse a un lobby

Esta parte de la guía muestra cómo unirse a un lobby existente creado por otro cliente.

1. Abra el script HelloMultiplayerLogic.cs. En el método OnLoginSuccess, agregue el siguiente código para unirse a un lobby:

   ```csharp theme={null}
   PFEntityKey entityKey = ...; // PlayFab user's entity key

   string connectionString = "<your lobby connection string>";

   PlayFabMultiplayer.JoinLobby(
           entityKey,
           connectionString,
           null);
   ```

2. Para definir un evento que se desencadene cuando su cliente local se una al lobby, agregue el siguiente código al método `OnLoginSuccess`:

   ```csharp theme={null}
   PlayFabMultiplayer.OnLobbyJoinCompleted += this.PlayFabMultiplayer_OnLobbyJoinCompleted;
   ```

3. Para definir el controlador de eventos OnLobbyJoinCompleted, agregue el siguiente código a la clase:

   ```csharp theme={null}
   private void PlayFabMultiplayer_OnLobbyJoinCompleted(Lobby lobby, PFEntityKey newMember, int reason)
   {
       if (LobbyError.SUCCEEDED(reason))
       {
           // Successfully joined a lobby
           Debug.Log("Joined a lobby");
       }
       else
       {
           // Error joining a lobby
           Debug.Log("Error joining a lobby");
       }
   }
   ```

4. Guarde y seleccione Play en el editor de Unity. La cadena "Joined a lobby" se muestra en la ventana Console.

## Buscar lobbies

Esta parte de la guía muestra cómo buscar lobbies existentes creados por otros clientes.

1. Abra el script HelloMultiplayerLogic.cs. En el método OnLoginSuccess, agregue el siguiente código para buscar lobbies:

   ```csharp theme={null}
   PFEntityKey entityKey = ...; // PlayFab user's entity key

   LobbySearchConfiguration config = new LobbySearchConfiguration();
   PlayFabMultiplayer.FindLobbies(entityKey, config);
   ```

2. Para definir un evento que se desencadene cuando su cliente local encuentre lobbies, agregue el siguiente código al método `OnLoginSuccess`:

   ```csharp theme={null}
   PlayFabMultiplayer.OnLobbyFindLobbiesCompleted += this.PlayFabMultiplayer_OnLobbyFindLobbiesCompleted;
   ```

3. Para definir el controlador de eventos OnLobbyFindLobbiesCompleted, agregue el siguiente código a la clase:

   ```csharp theme={null}
   private void PlayFabMultiplayer_OnLobbyFindLobbiesCompleted(
       IList<LobbySearchResult> searchResults, 
       PFEntityKey newMember, 
       int reason)
   {
       if (LobbyError.SUCCEEDED(reason))
       {
           // Successfully found lobbies
           Debug.Log("Found lobbies");

           // Iterate through lobby search results
           foreach (LobbySearchResult result in searchResults)
           {
               // Examine a search result
           }
       }
       else
       {
           // Error finding lobbies
           Debug.Log("Error finding lobbies");
       }
   }
   ```

4. Guarde y seleccione Play en el editor de Unity. La cadena "Found lobbies" se muestra en la ventana Console.

## Crear un ticket de matchmaking

Esta parte de la guía muestra cómo crear un ticket de matchmaking. Ejecútela junto con el escenario "Unirse a un ticket de matchmaking" en otro cliente, más abajo.

1. Abra el script HelloMultiplayerLogic.cs. En el método `OnLoginSuccess`, agregue el siguiente código para crear un ticket de matchmaking:

   ```csharp theme={null}
   PFEntityKey entityKey = ...; // PlayFab user's entity key
   PFEntityKey remoteEntityKey = ...; // another PlayFab user's entity key
   string remoteUserAttributesJson = ...; // JSON string with another PlayFab user's attributes for matchmaking

   PlayFabMultiplayer.OnMatchmakingTicketStatusChanged += PlayFabMultiplayer_OnMatchmakingTicketStatusChanged;

   List<MatchUser> localUsers = new List<MatchUser>();
   localUsers.Add(new MatchUser(entityKey, remoteUserAttributesJson));

   List<PFEntityKey> membersToMatchWith = new List<PFEntityKey>();
   membersToMatchWith.Add(remoteEntityKey);

   PlayFabMultiplayer.CreateMatchmakingTicket(
       localUsers,
       "QuickMatchQueueName",
       membersToMatchWith);
   ```

2. Para definir el controlador de eventos OnMatchmakingTicketStatusChanged, agregue el siguiente código a la clase:

   ```csharp theme={null}
   private void PlayFabMultiplayer_OnMatchmakingTicketStatusChanged(MatchmakingTicket ticket)
   {
       // Store and print matchmaking ticket
       Debug.Log(ticket.TicketId);

       // Examine matchmaking ticket status
       Debub.Log(ticket.Status)

       // Share matchmaking ticket with other clients taking part in matchmaking

       // Examine ticket
   }
   ```

3. Guarde y seleccione Play en el editor de Unity.

Si se especifica membersToMatchWith, se desencadenará un controlador de eventos OnMatchmakingTicketStatusChanged y el estado (Status) será WaitingForPlayers. En ese caso, una vez que otro cliente llame a JoinMatchmakingTicketFromId, se desencadenará un nuevo controlador de eventos OnMatchmakingTicketStatusChanged y esta vez el estado será WaitingForMatch.

De lo contrario, se desencadenará un controlador de eventos OnMatchmakingTicketStatusChanged y el estado será WaitingForMatch.

## Unirse a un ticket de matchmaking

Esta parte de la guía muestra cómo unirse a un ticket de matchmaking existente creado por otro cliente. Ejecútela junto con el escenario "Crear un ticket de matchmaking" en otro cliente, más arriba.

1. Abra el script HelloMultiplayerLogic.cs. En el método OnLoginSuccess, agregue el siguiente código para unirse a un ticket de matchmaking:

   ```csharp theme={null}
   PFEntityKey entityKey = ...; // PlayFab user's entity key
   string ticketId = ...; // Matchmaking ticket obtained from the client that created the ticket

   PlayFabMultiplayer.OnMatchmakingTicketCompleted += PlayFabMultiplayer_OnMatchmakingTicketStatusChanged;

   // Create JSON string with PlayFab user's attributes for matchmaking. This will need to be shared with other clients taking part in matchmaking
   string uniqueId = System.Guid.NewGuid().ToString();
   string userAttributesJson = "{\"MatchIdentifier\": \"" + uniqueId + "\"}";

   PlayFabMultiplayer.JoinMatchmakingTicketFromId(
       new MatchUser(entityKey, userAttributesJson),
       ticketId,
       "QuickMatchQueueName",
       new List<PFEntityKey>());
   ```

2. Para definir el controlador de eventos OnMatchmakingTicketStatusChanged, agregue el siguiente código a la clase:

   ```csharp theme={null}
   private void PlayFabMultiplayer_OnMatchmakingTicketStatusChanged(MatchmakingTicket ticket)
   {
       // Store and print matchmaking ticket
       Debug.Log(ticket.TicketId);

       // Examine matchmaking ticket status
       Debub.Log(ticket.Status)

       // Share matchmaking ticket with other clients taking part in matchmaking

       // Examine ticket
   }
   ```

3. Guarde y seleccione Play en el editor de Unity.

Se desencadenará un OnMatchmakingTicketStatusChanged con el estado WaitingForMatch.

## Completar un ticket de matchmaking

Esta parte de la guía muestra cómo se completa el matchmaking. Ejecútela junto con el escenario "Crear un ticket de matchmaking" en otro cliente, más arriba. Opcionalmente, puede ejecutarla con el escenario "Unirse a un ticket de matchmaking".

1. Se encontrará una coincidencia cuando varios tickets de la misma cola sean aptos para emparejarse. En ese caso,
   se desencadena el controlador de eventos OnMatchmakingTicketCompleted.

2. Suscríbase al controlador OnMatchmakignTicketCompleted

   ```csharp theme={null}
   PlayFabMultiplayer.OnMatchmakingTicketCompleted += PlayFabMultiplayer_OnMatchmakingTicketCompleted;
   ```

3. Para definir el controlador de eventos OnMatchmakingTicketCompleted, agregue el siguiente código a la clase:

   ```csharp theme={null}
   private void PlayFabMultiplayer_OnMatchmakingTicketCompleted(MatchmakingTicket ticket, int result)
   {
       if (LobbyError.SUCCEEDED(result))
       {
           // Successfully completed matchmaking ticket
           Debug.Log("Completed matchmaking ticket");

           // Examine matchmaking details
           MatchmakingMatchDetails details = ticket.GetMatchDetails();
       }
       else
       {
           // Error completing a matchmaking ticket
           Debug.Log("Error completing a matchmaking ticket");
       }
   }
   ```


## Related topics

- [Inicio rápido del complemento de Party para Unity](/es/services/playfab/multiplayer/networking/party-unity-plugin-quickstart.md)
- [Inicio rápido de Unity](/es/services/playfab/sdks/unity3d/quickstart.md)
- [Inicio rápido del SDK de Lobby](/es/services/playfab/multiplayer/lobby/lobby-getting-started.md)
- [Inicio rápido del SDK de Matchmaking](/es/services/playfab/multiplayer/matchmaking/quickstart-client-sdk.md)
- [Integración del complemento de PlayFab del Marketplace de Unreal Engine](/es/services/playfab/multiplayer/networking/party-unreal-engine-oss-playfab-plugin-integration.md)
