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

# Unreal Engine 快速入门

> 安装 PlayFab Unreal Marketplace 插件，并使用 C++ 或 Blueprints 从 Unreal Engine 项目中进行首次 PlayFab API 调用。

# 快速入门：Unreal Engine 的 PlayFab 客户端库

开始使用适用于 Unreal Engine 的 PlayFab 插件。按照本快速入门安装 PlayFab Unreal Engine 插件，并创建使用 C++ 客户端库和 Blueprint 接口的示例应用。

您可以使用适用于 Unreal Engine 的 PlayFab 插件来管理 Title 的 LiveOps，并执行管理员、客户端和服务器操作，例如：

* 玩家身份验证。
* 管理虚拟物品和货币。
* 创建社交功能，如好友列表。

  [API 参考文档](/services/playfab/api-references) | [库源代码](https://github.com/PlayFab/UnrealMarketplacePlugin) | [Unreal Marketplace](https://www.unrealengine.com/marketplace/playfab-sdk)

## 先决条件

* [PlayFab 开发者帐户](https://developer.playfab.com)。
* 已安装并配置为支持 Unreal Engine 的 [Visual Studio](https://visualstudio.microsoft.com/downloads/)。有关配置 Visual Studio 的信息，请参阅 [Setting Up Visual Studio for Unreal Engine](https://docs.unrealengine.com/en-US/Programming/Development/VisualStudioSetup/index.html)。
* 已安装 [Unreal Engine](https://www.unrealengine.com/download)。有关安装 Unreal Engine 的信息，请参阅 [Unreal Engine 安装指南](https://docs.unrealengine.com/4.27/en-US/Basics/Projects/Browser/)。
* 已安装 PlayFab Unreal 插件。您可以从 [Unreal Engine marketplace](https://www.unrealengine.com/marketplace/playfab-sdk) 安装 Unreal 插件。

## 创建 Unreal 项目

在 Unreal Engine 中，创建一个新的 Unreal 项目。有关详细说明，请参阅 [Create a New Project guide](https://docs.unrealengine.com/4.27/en-US/Basics/Projects/Browser/)。

1. 对于 **Project Category** 选择 **Games**。
2. 在 **Select Template** 中，选择 **Blank**。
3. 在 **Project Settings** 中，选择 **C++** 或 **Blueprint**。
4. 选择 **No Starter Content**。
5. 为您的项目选择一个名称，例如 **MyProject**。

## 在 Unreal 项目中启用 PlayFab 插件

要启用 PlayFab 插件：

1. 从 **Settings** 菜单，在 **Game Specific Settings** 下选择 **Plugins**。
2. 启用 **PlayFab** 插件并根据需要重新启动 Unreal Engine。

如果 **Plugins** 中未出现 "PlayFab"，请确认已从 Unreal Marketplace 安装该插件。重新启动 Unreal Editor。然后再次打开 **Plugins** 并搜索 "PlayFab"。

### 在 C++ 中将 PlayFab 添加为模块依赖项

在 Visual Studio 中，将 PlayFab 添加为 C++ 项目的模块依赖项：

1. 从 **View** 菜单打开 **Solution Explorer**，该窗口显示您的 C++ 项目文件。

2. 在 Solution Explorer 中，导航到 **Solution\Games\YourProjectName\Source** 并打开 **YourProjectName.Build.cs**。

3. 添加以下行：

   ```cpp theme={null}
   PrivateDependencyModuleNames.AddRange(new string[] { "PlayFab", "PlayFabCpp", "PlayFabCommon" });
   ```

4. 保存您的更改。

## 生成所需的 Visual Studio 项目文件

要更新并生成使用 PlayFab 插件所需的 Visual Studio 项目文件：

1. 打开文件资源管理器窗口并导航到项目文件所在的文件夹。
2. 在项目的根文件夹中，右键单击 YourProjectName.uproject 文件。
3. 从上下文菜单中，选择 **Generate Visual Studio project files**。

## 使用 C++ 调用 PlayFab

以下步骤将引导您创建一个使用自定义 ID 登录 PlayFab 的 Tile。有关从 Blueprints 项目登录的信息，请参阅本文后面的 "从 Unreal Blueprints 调用 PlayFab"。

### 创建新的 Actor

要创建新的 Actor：

1. 从 **File** 菜单，选择 **New C++ Class**。
2. 对于 **Parent Class** 选择 **Actor**。
3. 将您的 actor 命名为 **LoginActor**。创建 Actor 后，Unreal Engine 会自动打开您的 C++ 开发环境并加载 LoginActor.cpp 和 LoginActor.h。

<Info>
  在本快速入门中，您必须将 Actor 命名为 **LoginActor**。如果您给 Actor 使用不同的名称，则必须更新本快速入门中提供的示例代码以匹配新名称。
</Info>

4. 将您新创建的 Actor **LoginActor** 从 Content Browser 拖放到 Viewport 面板中。现在，它出现在 "World Outliner" 窗格中。
   如果您没有看到 **LoginActor**，请选择 **Show or hide the source panel** 图标。然后在 C++ 类下选择您的项目名称。

   <img src="https://mintcdn.com/microsoft-4404708b/N3T1ucKV7zIMBudj/images/playfab/sdks/unreal/show-login-actor.png?fit=max&auto=format&n=N3T1ucKV7zIMBudj&q=85&s=86853f5d47d5ca2a44dc0e9612204080" alt="Content browser showing the source panel icon." width="629" height="233" data-path="images/playfab/sdks/unreal/show-login-actor.png" />

<img src="https://mintcdn.com/microsoft-4404708b/N3T1ucKV7zIMBudj/images/playfab/sdks/unreal/login-actor-world.png?fit=max&auto=format&n=N3T1ucKV7zIMBudj&q=85&s=c46ab4ff0751332401e88629a8f058b3" alt="Login Actor in World" width="1062" height="524" data-path="images/playfab/sdks/unreal/login-actor-world.png" />

### 向您的 C++ LoginActor 添加 PlayFab API 调用

在本快速入门中，您使用 [LoginWithCustomID](xref:titleid.playfabapi.com.client.authentication.loginwithcustomid) 执行登录。虽然 `LoginWithCustomId` 易于开始使用，但我们建议在游戏发布时改用更安全的玩家身份验证方法。有关实现健壮登录功能的信息，请参阅 [Login basics and best practices](/services/playfab/identity/player-identity/login/login-basics-best-practices)。

`LoginWithCustomID` 调用是在您的 **LoginActor** 中进行的。要将 PlayFab 特定代码添加到您的 **LoginActor**：

1. 将 LoginActor.h 的内容替换为所示的代码：

```cpp theme={null}
#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "PlayFab.h"
#include "Core/PlayFabError.h"
#include "Core/PlayFabClientDataModels.h"
#include "LoginActor.generated.h"

UCLASS()
class ALoginActor : public AActor
{
    GENERATED_BODY()
public:
    ALoginActor();
    virtual void BeginPlay() override;
    void OnSuccess(const PlayFab::ClientModels::FLoginResult& Result) const;
    void OnError(const PlayFab::FPlayFabCppError& ErrorResult) const;

    virtual void Tick(float DeltaSeconds) override;
private:
    PlayFabClientPtr clientAPI = nullptr;
};
```

2. 将 LoginActor.cpp 的内容替换为以下代码。

```cpp theme={null}
#include "LoginActor.h"
#include "Core/PlayFabClientAPI.h"

ALoginActor::ALoginActor()
{
    PrimaryActorTick.bCanEverTick = true;
}

void ALoginActor::BeginPlay()
{
    Super::BeginPlay();
    
    GetMutableDefault<UPlayFabRuntimeSettings>()->TitleId = TEXT("144");
    
    clientAPI = IPlayFabModuleInterface::Get().GetClientAPI();

    PlayFab::ClientModels::FLoginWithCustomIDRequest request;
    request.CustomId = TEXT("GettingStartedGuide");
    request.CreateAccount = true;

    clientAPI->LoginWithCustomID(request,
        PlayFab::UPlayFabClientAPI::FLoginWithCustomIDDelegate::CreateUObject(this, &ALoginActor::OnSuccess),
        PlayFab::FPlayFabErrorDelegate::CreateUObject(this, &ALoginActor::OnError)
    );
}

void ALoginActor::OnSuccess(const PlayFab::ClientModels::FLoginResult& Result) const
{
    UE_LOG(LogTemp, Log, TEXT("Congratulations, you made your first successful API call!"));
}

void ALoginActor::OnError(const PlayFab::FPlayFabCppError& ErrorResult) const
{
    UE_LOG(LogTemp, Error, TEXT("Something went wrong with your first API call.\nHere's some debug information:\n%s"), *ErrorResult.GenerateErrorReport());
}

void ALoginActor::Tick(float DeltaTime)
{
    Super::Tick(DeltaTime);
}
```

<Tip>
  Visual Studio 中的 Intellisense 会指示它无法找到 include 文件和 PlayFab 命名空间。您可以放心地忽略这些警告。运行项目时，它将正确构建并执行。
</Tip>

### 使用 C++ 完成并执行

现在，您已准备好在 Unreal Engine 中使用 C++ 测试对 PlayFab 的调用。测试调用的结果显示在 Unreal Engine 的 **Output Log** 中。

在 Unreal Engine 中：

1. 从 **Windows** 菜单显示 Output Log，选择 **Developer Tools** 并启用 **Output Log**。
2. 在工具栏中，选择 **Compile** 并等待 Unreal Engine 完成编译。在您的代码编译期间，Unreal 会显示 "Compiling C++ Code."。
3. 选择 **Play**。代码运行时，Unreal 会在 **Output Log** 窗口中显示以下内容：

`LogTemp: Congratulations, you made your first successful API call!`

<img src="https://mintcdn.com/microsoft-4404708b/N3T1ucKV7zIMBudj/images/playfab/sdks/unreal/call-works.png?fit=max&auto=format&n=N3T1ucKV7zIMBudj&q=85&s=d87c28c4bd68f5b72bcb59366eacb795" alt="Output Log successful call" width="1477" height="311" data-path="images/playfab/sdks/unreal/call-works.png" />

## 从 Unreal Blueprints 调用 PlayFab

本节将引导您创建一个 Blueprint 结构，它使用 PlayFab API 调用 [LoginWithCustomID](https://learn.microsoft.com/en-us/rest/api/playfab/client/authentication/login-with-custom-id?view=playfab-rest\&preserve-view=true)。虽然 `LoginWithCustomId` 易于开始使用，但我们建议在游戏发布时改用更安全的玩家身份验证方法。有关实现健壮登录功能的信息，请参阅 [Login basics and best practices](/services/playfab/identity/player-identity/login/login-basics-best-practices)。

<Tip>
  如果您从 Blueprint 项目开始，则必须将其转换为 C++ 项目，PlayFab Blueprint Actions 才能起作用。
</Tip>

### 创建 Blueprint 结构

在 Unreal Engine 中，从工具栏中选择 **Open Level Blueprint**。

<img src="https://mintcdn.com/microsoft-4404708b/N3T1ucKV7zIMBudj/images/playfab/sdks/unreal/uemk-open-lv-bp.jpg?fit=max&auto=format&n=N3T1ucKV7zIMBudj&q=85&s=d80f85c201032ab8d0394e7a1a89e28e" alt="example open blueprint level image" width="439" height="439" data-path="images/playfab/sdks/unreal/uemk-open-lv-bp.jpg" />

EventGraph 打开并预填充了两个 Actions：`Event BeginPlay` 和 `Event Tick`。

本快速入门中使用的 Actions：

* `Set Play Fab Settings`
* `Login with Custom ID`
* `Make ClientLoginWithCustomIDRequest`
* `AddCustomEvent` x 2
* `Break PlayFabError`
* `Print String` x 2

按如下方式创建您的 Blueprint：

* 在 `Event BeginPlay` 上选择输出引脚并将其拖到 **Event Graph** 中的空白位置。在 **Executable Actions** 对话框中，搜索 `Set Play Fab Settings` 并选择它以将其添加到您的 Blueprint。在 `Set Play Fab Settings` 中，如果 **Game Title id** 为空，请将其设置为您游戏的 **Title ID**。

* 在 `Set Play Fab Settings` 上选择输出引脚并将其拖到空白位置。在 **Executable Actions** 对话框中，搜索 `Login with Custom ID` 并选择它以将其添加到您的 Blueprint。

* 在 `Login with Custom ID` 上选择 **Request** 引脚并将其拖到空白位置。从 **Actions providing a(n) Client Login With Custom ID Request Structure** 中，选择 `Make ClientLoginWithCustomIDRequest`。

* 在 `Make ClientLoginWithCustomIDRequest` 上：

  * 选择 **Create Account**。
  * 将 **Custom Id** 设置为 GettingStartedGuide。

* 在 `Login with Custom ID` 上，选择 **On Success** 引脚并将其拖到空白位置。在 **Actions providing a(n) Delegate** 中，搜索 `Add Custom Event` 并选择它以将其添加到您的 Blueprint。
  * 将其命名为 `OnLogin`。

* 选择 **On Failure** 引脚并将其拖到空白位置。在 **Actions providing a(n) Delegate** 中，搜索 `Add Custom Event` 并选择它以将其添加到您的 Blueprint。
  * 将其命名为 `OnFailure`。

* 在 `OnLogin` 上选择输出引脚并将其拖到空白位置。在 **Executable Actions** 对话框中，搜索 `Print String` 并选择它以将其添加到 Blueprint。
  * 在 `Print String` 上，将 **In String** 值设置为 "Congratulations, you made your first successful PlayFab API call using Blueprint!"。

* 选择 `OnFailure` 的输出引脚并将其拖到空白位置。在 **Executable Actions** 对话框中，搜索 `Print String` 并选择它以将其添加到 Blueprint。

* 在 `OnFailure` 上选择 **Error** 引脚并将其拖到空白位置。在 **Actions providing a(n) string** 对话框中，搜索 **Break PlayFabError** 并选择它以将其添加到 Blueprint。在 **Actions taking a(n) PlayFab error structure** 对话框中，搜索 **Break PlayFabError** 并选择它以将其添加到 Blueprint。

* 将 `Break PlayFabError` 的 **Error Message** 引脚连接到失败时的 `Print String` Action 的 **In String** 引脚。

完成后，您的 Blueprint 应类似于此设计：

<img src="https://mintcdn.com/microsoft-4404708b/N3T1ucKV7zIMBudj/images/playfab/sdks/unreal/blueprint-structure.png?fit=max&auto=format&n=N3T1ucKV7zIMBudj&q=85&s=28dcddff9746a46c9f2719b2439d4b84" alt="Opened Blueprint UI" width="1958" height="1502" data-path="images/playfab/sdks/unreal/blueprint-structure.png" />

**保存** Blueprint，然后关闭 Blueprint Editor 窗口。

### 使用 Blueprint 执行 PlayFab 调用

1. 在工具栏上，选择 **Play** 按钮。

2. 当 Blueprint 运行时，Viewport 窗口中会显示以下输出。

   <img src="https://mintcdn.com/microsoft-4404708b/N3T1ucKV7zIMBudj/images/playfab/sdks/unreal/uemk-log-success.png?fit=max&auto=format&n=N3T1ucKV7zIMBudj&q=85&s=190c17886fa54873449808f5bbab7fc3" alt="Blueprint log success" width="489" height="221" data-path="images/playfab/sdks/unreal/uemk-log-success.png" />

恭喜，您已使用 Blueprint 成功进行了首次 PlayFab API 调用！

## 更多资源

* Unreal Engine 关于 [Blueprints Visual Scripting](https://docs.unrealengine.com/en-US/Engine/Blueprints/index.html) 的文档。
* [Unreal Engine 文档](https://docs.unrealengine.com/)。


## Related topics

- [PlayFab 支持的游戏引擎](/zh-CN/services/playfab/sdks/game-engines/index.md)
- [PlayFab 2018 版本发布说明](/zh-CN/services/playfab/release-notes/2018.md)
- [PlayFab Online Subsystem (OSS) 快速入门](/zh-CN/services/playfab/multiplayer/networking/party-unreal-engine-oss-quickstart.md)
- [Matchmaking SDK 快速入门](/zh-CN/services/playfab/multiplayer/matchmaking/quickstart-client-sdk.md)
- [Lobby SDK 快速入门](/zh-CN/services/playfab/multiplayer/lobby/lobby-getting-started.md)
