> ## 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.

# Démarrage rapide du plugiciel Multiplayer pour Unity

> Installez le plugiciel Unity PlayFab Multiplayer et effectuez vos premiers appels d'API Lobby et Matchmaking depuis un projet Unity, avec des remarques sur la configuration GDK.

# Démarrage rapide : plugiciel Unity PlayFab Multiplayer

Commencez à utiliser le plugiciel Unity PlayFab Multiplayer. Suivez les étapes ci-dessous pour installer le package et essayer un exemple de code pour une tâche de base.

Ce démarrage rapide vous aide à effectuer vos premiers appels d'API à l'aide du SDK PlayFab Multiplayer pour Unity. Avant de continuer, veillez à suivre le [démarrage rapide : bibliothèque cliente PlayFab pour C# dans Unity](/fr-CA/services/playfab/sdks/unity3d/quickstart), qui garantit que vous disposez d'un compte PlayFab et que vous savez vous connecter à PlayFab depuis votre jeu et depuis PlayFab Game Manager.

<Note>
  Si vous prévoyez d'utiliser ce plugiciel pour développer des jeux basés sur le Microsoft Game Development Kit (GDK), vous devez vous procurer et installer le GDK séparément. Consultez également les informations sur le module complémentaire Unity pour Game Core sur les consoles XBOX.
</Note>

## Configuration requise

* Un [compte de développeur PlayFab](https://developer.playfab.com).

* Une copie installée de l'éditeur Unity. Pour installer Unity pour un usage personnel au moyen d'Unity Hub, ou Unity+ pour un usage professionnel, consultez [Download Unity](https://unity3d.com/get-unity/download). Vérifiez si nécessaire la prise en charge d'Unity dans la documentation de votre plateforme. La version minimale d'Unity prise en charge est Unity 2017 LTS.

* Un projet Unity, qui peut être l'un des suivants :

  * Un tout nouveau projet : pour plus de renseignements, consultez [Démarrer Unity pour la première fois](/fr-CA/services/playfab/sdks/unity3d/quickstart).
  * Un projet de tutoriel guidé. Pour plus de renseignements, consultez [Getting Started with Unity](https://learn.unity.com/).
  * Un projet existant.

* Le SDK Unity3D PlayFab « principal » (également inclus dans le plugiciel Multiplayer pour Unity). Pour plus de renseignements sur l'installation du SDK Unity3D, consultez la section « Télécharger et installer le SDK PlayFab » du [démarrage rapide : bibliothèque cliente PlayFab pour C# dans Unity](/fr-CA/services/playfab/sdks/unity3d/quickstart#download-and-install-playfab-sdk).

## Télécharger et installer le plugiciel Unity PlayFab Multiplayer

Suivez ces étapes pour télécharger et installer le plugiciel Unity PlayFab Multiplayer.

1. Téléchargez le package d'assets PlayFab [Multiplayer Unity Plugin](https://github.com/PlayFab/PlayFabMultiplayerUnity) (utilisez le point de distribution correspondant à votre plateforme).
2. **Important!** Consultez les informations du fichier README publié avec le plugiciel. Il est adapté à chaque version et peut contenir des instructions importantes propres à votre plateforme.
3. Ouvrez votre projet Unity.
4. Accédez à l'emplacement où vous avez enregistré le fichier .unitypackage et double-cliquez dessus pour ouvrir la boîte de dialogue d'importation.
5. Pour importer le plugiciel Unity PlayFab Multiplayer dans votre projet, sélectionnez **Import**.

Remarque : vous devrez peut-être installer une version plus récente du SDK Unity PlayFab « principal » si nécessaire.

## Configurer votre scène

Cette partie du guide vous montre comment ajouter `PlayfabMultiplayerEventProcessor` à votre scène afin de pouvoir appeler les API PlayFab Multiplayer depuis Unity.

Avant de pouvoir utiliser l'API Multiplayer, un **joueur PlayFab doit être connecté**. Pour plus de renseignements sur la connexion d'un joueur, consultez [Effectuer votre premier appel d'API dans le démarrage rapide : bibliothèque cliente PlayFab pour C# dans Unity](/fr-CA/services/playfab/sdks/unity3d/quickstart#making-your-first-api-call).

1. Dans l'éditeur Unity, dans la fenêtre Project, accédez à **Assets > PlayFabMultiplayerSDK > Prefabs**.

2. Depuis le dossier Prefabs, faites glisser **PlayfabMultiplayerEventProcessor** dans votre scène, dans la fenêtre **Hierarchy**.

3. Créez dans votre scène un Game Object vide appelé « HelloMultiplayerLogic ».

4. Sélectionnez le Game Object HelloMultiplayerLogic pour ouvrir l'**Inspector**.

5. Sélectionnez **Add Component**.

6. Tapez « HelloMultiplayerLogic » et appuyez sur Entrée pour afficher le menu de nouveau script.

7. Appuyez de nouveau sur Entrée pour créer le nouveau script, HelloMultiplayerLogic.cs.

8. Trouvez le script dans la fenêtre **Project** et double-cliquez dessus pour le modifier.

9. Ajoutez les instructions using suivantes à votre script :

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

10. Ajoutez le code suivant dans la méthode Start pour vous connecter à PlayFab.

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

11. Ajoutez les méthodes suivantes à la classe.

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

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

<Note>
  Vous pourriez recevoir les erreurs suivantes : `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>

Le Microsoft GDK et Windows ne prennent en charge que x64.

Pour résoudre ces problèmes :

1. Dans l'éditeur Unity, sélectionnez **File > Build Settings.**
2. Sélectionnez votre plateforme. Ensuite, dans la liste déroulante **Architecture**, sélectionnez x86\_64 ou x64.
3. Sélectionnez **Player Settings.**
4. Dans le volet droit, sélectionnez Other Setting.
5. Trouvez le paramètre **Allow unsafe Code** et sélectionnez-le.
6. Fermez les fenêtres **Build Settings** et **Project Settings**.

## Créer et rejoindre un lobby

Cette partie du guide vous montre comment créer et rejoindre un lobby.

1. Ouvrez le script HelloMultiplayerLogic.cs. Dans la méthode `OnLoginSuccess`, ajoutez le code suivant pour créer et rejoindre un lobby :

   ```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. Pour définir le gestionnaire d'événements OnLobbyCreateAndJoinCompleted, ajoutez le code suivant à la classe :

   ```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. Pour définir le gestionnaire d'événements OnLobbyDisconnected, ajoutez le code suivant à la classe :

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

4. Enregistrez, puis sélectionnez Play dans l'éditeur Unity. La chaîne de connexion du lobby s'affiche dans la fenêtre Console.

## Rejoindre un lobby

Cette partie du guide vous montre comment rejoindre un lobby existant créé par un autre client.

1. Ouvrez le script HelloMultiplayerLogic.cs. Dans la méthode OnLoginSuccess, ajoutez le code suivant pour rejoindre un lobby :

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

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

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

2. Pour définir un événement qui se déclenche lorsque votre client local rejoint le lobby, ajoutez le code suivant à la méthode `OnLoginSuccess` :

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

3. Pour définir le gestionnaire d'événements OnLobbyJoinCompleted, ajoutez le code suivant à la classe :

   ```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. Enregistrez, puis sélectionnez Play dans l'éditeur Unity. La chaîne « Joined a lobby » s'affiche dans la fenêtre Console.

## Rechercher des lobbies

Cette partie du guide vous montre comment trouver des lobbies existants créés par d'autres clients.

1. Ouvrez le script HelloMultiplayerLogic.cs. Dans la méthode OnLoginSuccess, ajoutez le code suivant pour rechercher des lobbies :

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

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

2. Pour définir un événement qui se déclenche lorsque votre client local trouve des lobbies, ajoutez le code suivant à la méthode `OnLoginSuccess` :

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

3. Pour définir le gestionnaire d'événements OnLobbyFindLobbiesCompleted, ajoutez le code suivant à la classe :

   ```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. Enregistrez, puis sélectionnez Play dans l'éditeur Unity. La chaîne « Found lobbies » s'affiche dans la fenêtre Console.

## Créer un ticket de matchmaking

Cette partie du guide vous montre comment créer un ticket de matchmaking. Exécutez-la avec le scénario « Rejoindre un ticket de matchmaking » ci-dessous sur un autre client.

1. Ouvrez le script HelloMultiplayerLogic.cs. Dans la méthode `OnLoginSuccess`, ajoutez le code suivant pour créer 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. Pour définir le gestionnaire d'événements OnMatchmakingTicketStatusChanged, ajoutez le code suivant à la classe :

   ```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. Enregistrez, puis sélectionnez Play dans l'éditeur Unity.

Si membersToMatchWith est spécifié, un gestionnaire d'événements OnMatchmakingTicketStatusChanged est déclenché avec le statut WaitingForPlayers. Dans ce cas, dès qu'un autre client appelle JoinMatchmakingTicketFromId, un nouveau gestionnaire d'événements OnMatchmakingTicketStatusChanged est déclenché, cette fois avec le statut WaitingForMatch.

Sinon, un gestionnaire d'événements OnMatchmakingTicketStatusChanged est déclenché avec le statut WaitingForMatch.

## Rejoindre un ticket de matchmaking

Cette partie du guide vous montre comment rejoindre un ticket de matchmaking existant créé par un autre client. Exécutez-la avec le scénario « Créer un ticket de matchmaking » ci-dessus sur un autre client.

1. Ouvrez le script HelloMultiplayerLogic.cs. Dans la méthode OnLoginSuccess, ajoutez le code suivant pour rejoindre 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. Pour définir le gestionnaire d'événements OnMatchmakingTicketStatusChanged, ajoutez le code suivant à la classe :

   ```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. Enregistrez, puis sélectionnez Play dans l'éditeur Unity.

Un événement OnMatchmakingTicketStatusChanged est déclenché avec le statut WaitingForMatch.

## Finaliser un ticket de matchmaking

Cette partie du guide vous montre comment le matchmaking se termine. Exécutez-la avec le scénario « Créer un ticket de matchmaking » ci-dessus sur un autre client. Vous pouvez également l'exécuter avec le scénario « Rejoindre un ticket de matchmaking ».

1. Une partie est trouvée dès que plusieurs tickets de la même file d'attente peuvent être associés. Dans ce cas,
   le gestionnaire d'événements OnMatchmakingTicketCompleted est déclenché.

2. Abonnez-vous au gestionnaire OnMatchmakignTicketCompleted

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

3. Pour définir le gestionnaire d'événements OnMatchmakingTicketCompleted, ajoutez le code suivant à la classe :

   ```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

- [Démarrage rapide du plugiciel Party pour Unity](/fr-CA/services/playfab/multiplayer/networking/party-unity-plugin-quickstart.md)
- [Démarrage rapide Unity](/fr-CA/services/playfab/sdks/unity3d/quickstart.md)
- [Vue d'ensemble du plugiciel Party pour Unity](/fr-CA/services/playfab/multiplayer/networking/party-unity-overview.md)
- [Vue d'ensemble du plugiciel Unity PlayFab Multiplayer](/fr-CA/services/playfab/multiplayer/lobby/lobby-matchmaking-sdks/multiplayer-unity-overview.md)
- [Notes de version du plugiciel PlayFab Party pour Unity](/fr-CA/services/playfab/multiplayer/networking/party-unity-release-notes.md)
