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

# Multiplayer Unity 外掛程式快速入門

> 安裝 PlayFab Multiplayer Unity 外掛程式，並從 Unity 專案進行您的第一個 Lobby 和 Matchmaking API 呼叫，包括 GDK 設定考量事項。

# 快速入門：PlayFab Multiplayer Unity 外掛程式

開始使用 PlayFab Multiplayer Unity 外掛程式。請依照下列步驟安裝套件，並試用基本工作的範例程式碼。

本快速入門可協助您使用適用於 Unity 的 PlayFab Multiplayer SDK 進行第一個 API 呼叫。繼續之前，請確認您已完成[快速入門：Unity 中適用於 C# 的 PlayFab 用戶端程式庫](/zh-TW/services/playfab/sdks/unity3d/quickstart)，這可確保您擁有 PlayFab 帳戶，並熟悉如何從遊戲和 PlayFab Game Manager 登入 PlayFab。

<Note>
  如果您打算使用此外掛程式開發以 Microsoft Game Development Kit (GDK) 為基礎的遊戲，您需要另外取得並安裝 GDK。另請參閱有關 XBOX 主機上 Game Core 之 Unity 附加元件的詳細資料。
</Note>

## 需求

* [PlayFab 開發人員帳戶](https://developer.playfab.com)。

* 已安裝的 Unity 編輯器。若要透過 Unity Hub 安裝供個人使用的 Unity，或供專業使用的 Unity+，請參閱[下載 Unity](https://unity3d.com/get-unity/download)。如有需要，請查看您特定平台文件中的 Unity 支援。支援的最低 Unity 版本為 Unity 2017 LTS。

* Unity 專案 – 可以是下列任何一種：

  * 全新專案：如需詳細資訊，請參閱[第一次啟動 Unity](/zh-TW/services/playfab/sdks/unity3d/quickstart)。
  * 引導式教學課程專案。如需詳細資訊，請參閱 [Getting Started with Unity](https://learn.unity.com/)。
  * 現有專案。

* PlayFab「核心」Unity3D SDK (也包含在 Multiplayer Unity 外掛程式中)。如需安裝 Unity3D SDK 的相關資訊，請參閱[快速入門：Unity 中適用於 C# 的 PlayFab 用戶端程式庫](/zh-TW/services/playfab/sdks/unity3d/quickstart#download-and-install-playfab-sdk)的「下載並安裝 PlayFab SDK」一節。

## 下載並安裝 PlayFab Multiplayer Unity 外掛程式

依照下列步驟下載並安裝 PlayFab Multiplayer Unity 外掛程式。

1. 下載 PlayFab [Multiplayer Unity 外掛程式](https://github.com/PlayFab/PlayFabMultiplayerUnity) Asset 套件 (依您的平台使用對應的散發點)。
2. **重要！** 請參閱與外掛程式一起發佈的 README 檔案中的資訊。它是針對每個特定版本量身打造的，可能包含您平台專屬的重要指示。
3. 開啟您的 Unity 專案。
4. 瀏覽至您儲存 .unitypackage 的位置，然後按兩下以開啟匯入對話方塊。
5. 若要將 PlayFab Multiplayer Unity 外掛程式匯入您的專案，請選取 **Import**。

注意：如有必要，您可能需要安裝較新版本的 PlayFab「核心」Unity SDK。

## 設定您的場景

本指南的這一部分說明如何將 `PlayfabMultiplayerEventProcessor` 新增至您的場景，讓您能夠從 Unity 呼叫 PlayFab Multiplayer API。

在使用 Multiplayer API 之前，您**必須有已登入的 PlayFab 玩家**。如需登入玩家的相關資訊，請參閱[快速入門：Unity 中適用於 C# 的 PlayFab 用戶端程式庫中的進行您的第一個 API 呼叫](/zh-TW/services/playfab/sdks/unity3d/quickstart#making-your-first-api-call)。

1. 在 Unity 編輯器的 Project 視窗中，瀏覽至 **Assets > PlayFabMultiplayerSDK > Prefabs**。

2. 從 Prefabs 資料夾中，將 **PlayfabMultiplayerEventProcessor** 拖放到 **Hierarchy** 視窗中的場景。

3. 在場景中建立一個名為 "HelloMultiplayerLogic" 的空 Game Object。

4. 選取 HelloMultiplayerLogic Game Object 以開啟 **Inspector**。

5. 選取 **Add Component**。

6. 輸入 "HelloMultiplayerLogic" 並按 Enter 以顯示新指令碼功能表。

7. 再按一次 Enter 以建立新指令碼 HelloMultiplayerLogic.cs。

8. 在 **Project** 視窗中找到該指令碼，然後按兩下以編輯指令碼。

9. 將下列 using 陳述式新增至您的指令碼：

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

10. 在 Start 方法中新增下列程式碼以登入 PlayFab。

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

11. 將下列方法新增至類別。

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

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

<Note>
  您可能會收到下列錯誤：`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>

Microsoft GDK 和 Windows 只支援 x64。

若要解決這些問題：

1. 在 Unity 編輯器中，選取 **File > Build Settings.**
2. 選取您的平台。然後從 **Architecture** 下拉式清單中，選取 x86\_64 或 x64。
3. 選取 **Player Settings.**
4. 在右窗格中，選取 Other Setting。
5. 找到 **Allow unsafe Code** 設定並選取它。
6. 關閉 **Build Settings** 和 **Project Settings** 視窗。

## 建立並加入大廳

本指南的這一部分說明如何建立並加入大廳。

1. 開啟 HelloMultiplayerLogic.cs 指令碼。在 `OnLoginSuccess` 方法中，新增下列程式碼以建立並加入大廳：

   ```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. 若要定義 OnLobbyCreateAndJoinCompleted 事件處理常式，請將下列程式碼新增至類別：

   ```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. 若要定義 OnLobbyDisconnected 事件處理常式，請將下列程式碼新增至類別：

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

4. 儲存並在 Unity 編輯器中選取 Play。大廳連接字串會顯示在 Console 視窗中。

## 加入大廳

本指南的這一部分說明如何加入其他用戶端所建立的現有大廳。

1. 開啟 HelloMultiplayerLogic.cs 指令碼。在 OnLoginSuccess 方法中，新增下列程式碼以加入大廳：

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

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

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

2. 若要定義在本機用戶端加入大廳時觸發的事件，請將下列程式碼新增至 `OnLoginSuccess` 方法：

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

3. 若要定義 OnLobbyJoinCompleted 事件處理常式，請將下列程式碼新增至類別：

   ```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. 儲存並在 Unity 編輯器中選取 Play。字串 "Joined a lobby" 會顯示在 Console 視窗中。

## 尋找大廳

本指南的這一部分說明如何尋找其他用戶端所建立的現有大廳。

1. 開啟 HelloMultiplayerLogic.cs 指令碼。在 OnLoginSuccess 方法中，新增下列程式碼以尋找大廳：

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

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

2. 若要定義在本機用戶端找到大廳時觸發的事件，請將下列程式碼新增至 `OnLoginSuccess` 方法：

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

3. 若要定義 OnLobbyFindLobbiesCompleted 事件處理常式，請將下列程式碼新增至類別：

   ```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. 儲存並在 Unity 編輯器中選取 Play。字串 "Found lobbies" 會顯示在 Console 視窗中。

## 建立配對票證

本指南的這一部分說明如何建立配對票證。請在另一個用戶端上搭配下方的「加入配對票證」情境執行。

1. 開啟 HelloMultiplayerLogic.cs 指令碼。在 `OnLoginSuccess` 方法中，新增下列程式碼以建立配對票證：

   ```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. 若要定義 OnMatchmakingTicketStatusChanged 事件處理常式，請將下列程式碼新增至類別：

   ```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. 儲存並在 Unity 編輯器中選取 Play。

如果指定了 membersToMatchWith，會觸發一個 OnMatchmakingTicketStatusChanged 事件處理常式，且 Status 會是 WaitingForPlayers。在此情況下，一旦另一個用戶端呼叫 JoinMatchmakingTicketFromId，就會觸發新的 OnMatchmakingTicketStatusChanged 事件處理常式，而這次的狀態會是 WaitingForMatch。

否則，會觸發一個 OnMatchmakingTicketStatusChanged 事件處理常式，且狀態會是 WaitingForMatch。

## 加入配對票證

本指南的這一部分說明如何加入其他用戶端所建立的現有配對票證。請在另一個用戶端上搭配上方的「建立配對票證」情境執行。

1. 開啟 HelloMultiplayerLogic.cs 指令碼。在 OnLoginSuccess 方法中，新增下列程式碼以加入配對票證：

   ```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. 若要定義 OnMatchmakingTicketStatusChanged 事件處理常式，請將下列程式碼新增至類別：

   ```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. 儲存並在 Unity 編輯器中選取 Play。

會觸發一個 OnMatchmakingTicketStatusChanged，且 Status 為 WaitingForMatch。

## 完成配對票證

本指南的這一部分說明配對是如何完成的。請在另一個用戶端上搭配上方的「建立配對票證」情境執行。您也可以選擇搭配「加入配對票證」情境執行。

1. 一旦同一佇列中的多張票證符合配對資格，就會找到比賽。在此情況下，
   會觸發 OnMatchmakingTicketCompleted 事件處理常式。

2. 訂閱 OnMatchmakignTicketCompleted 處理常式

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

3. 若要定義 OnMatchmakingTicketCompleted 事件處理常式，請將下列程式碼新增至類別：

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

- [Party Unity 外掛程式快速入門](/zh-TW/services/playfab/multiplayer/networking/party-unity-plugin-quickstart.md)
- [整合 PlayFab Unreal Engine Marketplace 外掛程式](/zh-TW/services/playfab/multiplayer/networking/party-unreal-engine-oss-playfab-plugin-integration.md)
- [Unity 快速入門](/zh-TW/services/playfab/sdks/unity3d/quickstart.md)
- [PlayFab Multiplayer Unity 外掛程式概觀](/zh-TW/services/playfab/multiplayer/lobby/lobby-matchmaking-sdks/multiplayer-unity-overview.md)
- [推播通知快速入門](/zh-TW/services/playfab/live-service-management/game-configuration/title-communications/push-notifications/quickstart.md)
