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

# 教程：获取玩家个人资料

> 在 Unity 中使用 GetPlayerProfile 检索 PlayFab 玩家个人资料数据，配置 PlayerProfileViewConstraints，并读取创建时间和上次登录时间戳。

# 教程：获取玩家个人资料

在本教程中，您将学习如何：

<Note>
  \[!div class="checklist"] \* 创建具有显示名称的用户 \* 调用玩家个人资料 \* 获取玩家创建时间和上次登录时间 \* 为作品配置玩家个人资料视图约束 \* 通过登录操作获取玩家个人资料
</Note>

## 要求

* 一个 [PlayFab 开发者帐户](https://developer.playfab.com)。
* 已安装的 Unity 编辑器。若要通过 Unity Hub 安装 Unity 个人版，或安装用于专业用途的 Unity+，请参阅 [下载 Unity](https://unity3d.com/get-unity/download)。

<Note>
  PlayFab Unity3D SDK 支持 Unity 编辑器版本 5.3（2015 年 12 月发布）及更高版本。
</Note>

* 一个 Unity 项目 \* 可以是以下任一项：
  * 一个全新项目。有关更多信息，请参阅[首次启动 Unity](https://docs.unity3d.com/550/Documentation/Manual/GettingStarted.html)。
  * 一个引导式教程项目。有关更多信息，请参阅 [Unity 入门](https://learn.unity.com/)。
  * 一个现有项目。
* PlayFab [Unity3D SDK](/services/playfab/sdks/unity3d)。

在本教程中，需要了解如何为您的作品创建玩家的基本知识，以便您可以对玩家执行 `GetPlayerProfile`。

如果您不熟悉 Game Manager，还值得阅读 [Game Manager 快速入门](/services/playfab/live-service-management/gamemanager/quickstart)，因为这是我们配置个人资料约束的地方。

本文中的 C# 示例是为 Unity SDK 编写的。Unity SDK 使用事件驱动模型来处理非同步任务。要使用 C# SDK 运行示例代码，您必须修改代码以使用异步任务模型。需要修改的方法在其签名中的方法名称上附加了 Async。例如，Unity SDK 中的 SetObject 在 C# SDK 中变为 SetObjectAsync。有关更多信息，请参阅[使用 async 和 await 进行异步编程](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/async/)。

## 创建具有显示名称的用户

第一步是创建玩家并为用户添加显示名称。此示例将创建一个显示名称为 `UnicornTossMaster` 的新用户。

```csharp theme={null}
void CreatePlayerAndUpdateDisplayName() {
    PlayFabClientAPI.LoginWithCustomID( new LoginWithCustomIDRequest {
        CustomId = "PlayFabGetPlayerProfileCustomId",
        CreateAccount = true
    }, result => {
        Debug.Log("Successfully logged in a player with PlayFabId: " + result.PlayFabId);
        UpdateDisplayName();
    }, error => Debug.LogError(error.GenerateErrorReport()));
}

void UpdateDisplayName() {
    PlayFabClientAPI.UpdateUserTitleDisplayName( new UpdateUserTitleDisplayNameRequest {
        DisplayName = "UnicornTossMaster"
    }, result => {
        Debug.Log("The player's display name is now: " + result.DisplayName);
    }, error => Debug.LogError(error.GenerateErrorReport()));
}
```

控制台输出应显示：

```
Successfully logged in a player with PlayFabId: SOME_PLAYFAB_ID
The player's display name is now: UnicornTossMaster
```

## 调用玩家个人资料

下一步是使用为该玩家创建一个非常基本的个人资料

以下示例使用了基本的 [GetPlayerProfile](xref:titleid.playfabapi.com.server.accountmanagement.getplayerprofile) 调用。

```csharp theme={null}
void GetPlayerProfile(string playFabId) {
    PlayFabClientAPI.GetPlayerProfile( new GetPlayerProfileRequest() {
        PlayFabId = playFabId,
        ProfileConstraints = new PlayerProfileViewConstraints() {
            ShowDisplayName = true
        }
    },
    result => Debug.Log("The player's DisplayName profile data is: " + result.PlayerProfile.DisplayName),
    error => Debug.LogError(error.GenerateErrorReport()));
}
```

响应包含一个 [PlayerProfileModel](xref:titleid.playfabapi.com.server.accountmanagement.getplayerprofile#playerprofilemodel) 对象，其中包含玩家的显示名称 `UnicornTossMaster`。

## 获取玩家创建时间和上次登录时间

在 [PlayerProfileModel](xref:titleid.playfabapi.com.server.accountmanagement.getplayerprofile#playerprofilemodel) 对象中有相当多关于玩家的数据。在上一步中，发出了 `GetPlayerProfile`，接收到的响应仅包含显示名称信息。

下一步是获取玩家*更多*的个人资料数据。为此，请在 [PlayerProfileViewConstraints](xref:titleid.playfabapi.com.server.accountmanagement.getplayerprofile#playerprofileviewconstraints) 请求参数中调用带有额外字段的 `GetPlayerProfile`。

以下 **C#** 示例修改了步骤 2 中的 `GetPlayerProfile` 方法，并通过在 [ProfileConstraints](xref:titleid.playfabapi.com.server.accountmanagement.getplayerprofile#playerprofileviewconstraints) 中设置它们的标志来调用 `GetPlayerProfile` 请求 `Created` 和 `LastLogin` 字段。

<Note>
  **这一步中此调用将不成功！！！**
</Note>

```csharp theme={null}
void CreatePlayerAndUpdateDisplayName(string playFabId) {
    PlayFabClientAPI.GetPlayerProfile( new GetPlayerProfileRequest() {
        PlayFabId = playFabId,
        ProfileConstraints = new PlayerProfileViewConstraints {
            ShowDisplayName = true,
            ShowCreated = true,
            ShowLastLogin = true
        }
    },
    result => Debug.Log("The player's profile Created date is: " + result.PlayerProfile.Created),
    error => Debug.LogError(error.GenerateErrorReport()));
}
```

如果您此时运行此示例代码，它会返回一个带有 `Error Code 1303` 的错误。`RequestViewConstraintParamsNotAllowed`，以及一条错误消息，指出存在 `Invalid view constraints`，并以 JSON 输出作品当前设置的约束。

发生此错误是因为您尚未配置在作品的个人资料约束设置中显示 `Created` 和 `LastLogin` 的功能。

## 为作品配置玩家个人资料视图约束

要在调用 [GetPlayerProfile](xref:titleid.playfabapi.com.server.accountmanagement.getplayerprofile) API 时获取更多数据，您需要配置可用数据上的约束。这些设置在作品的 Game Manager 设置中。

默认情况下，**ALLOW CLIENT ACCESS TO PROFILE PROPERTIES:** 只启用了 **Display name**，从而允许您检索 **Display Name** 值。

要为作品配置其他约束：

* 在 [Game Manager](https://developer.playfab.com) 中，选择您的作品。
* 选择左上角的齿轮图标，然后选择 **Title settings**。
* 选择 **Client Profile Options** 选项卡。
* 要在 [ProfileConstraints](xref:titleid.playfabapi.com.server.accountmanagement.getplayerprofile#playerprofileviewconstraints) 中同时启用 **Created** 和 **LastLogin**，选中 **Creation date** 和 **Last login time**，然后选择 **SAVE CLIENT PROFILE OPTIONS**。

<img src="https://mintcdn.com/microsoft-4404708b/N3T1ucKV7zIMBudj/images/playfab/player-progression/player-data/tutorials/playfab-allow-client-access-to-profile-properties.png?fit=max&auto=format&n=N3T1ucKV7zIMBudj&q=85&s=e3bbe44c17680cdd24273e71fb2f7d80" alt="PlayFab 设置 * 客户端个人资料选项 * 允许客户端访问个人资料属性" width="1227" height="937" data-path="images/playfab/player-progression/player-data/tutorials/playfab-allow-client-access-to-profile-properties.png" />

现在，当您调用 1`CreatePlayerAndUpdateDisplayName` 时，它将返回带有用户创建时间、上次登录时间和显示名称 `UnicornTossMaster` 数据的 [PlayerProfileModel](xref:titleid.playfabapi.com.server.accountmanagement.getplayerprofile#playerprofilemodel) 对象。

## 通过登录操作获取玩家个人资料

在大多数情况下，您希望在玩家登录后立即检索玩家个人资料数据。PlayFab API 允许您将登录调用和检索玩家个人资料的调用合并为一次调用。

以下示例展示了如何通过登录请求获取个人资料信息，并使用 `LoginWithCustomId` 作为示例。

<Note>
  这适用于*所有*登录机制。
</Note>

```csharp theme={null}
void CreatePlayerAndUpdateDisplayName(string customId) {
    PlayFabClientAPI.LoginWithCustomID( new LoginWithCustomIDRequest() {
        CustomId = customId,
        // Define info request parameters
        InfoRequestParameters = new GetPlayerCombinedInfoRequestParams() {
            // And make sure PlayerProfile is included
            GetPlayerProfile = true,
            // Define rules for PlayerProfile request
            ProfileConstraints = new PlayerProfileViewConstraints() {
                // And make sure that both AvatarUrl and LastLogin are included.
                ShowAvatarUrl = true,
                ShowLastLogin = true,
            }
        }
    },
    result =>
    {
        // Extract the data you have requested
        var avatarUrl = result.InfoResultPayload.PlayerProfile.AvatarUrl;
    },
    error => Debug.LogError(error.GenerateErrorReport()));
}
```


## Related topics

- [player_updated_contact_email](/zh-CN/services/playfab/api-references/events/PlayerIdentity/player-updated-contact-email.md)
- [PFGetPlayerCombinedInfoRequestParams](/zh-CN/services/playfab/api-references/c/pftypes/structs/pfgetplayercombinedinforequestparams.md)
- [player_updated_login_email](/zh-CN/services/playfab/api-references/events/PlayerIdentity/player-updated-login-email.md)
- [跨网络多人游戏实现示例](/zh-CN/services/xbox-services/multiplayer/concepts/live-console-xr007-multiplayer-example.md)
- [player_tag_added](/zh-CN/services/playfab/api-references/events/PlayerIdentity/player-tag-added.md)
