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

# 通过 CloudScript 修改只读或内部玩家数据

> 使用 server.UpdateUserInternalData 从 CloudScript 安全地更新只读和内部 PlayFab 玩家数据,附带 C# 和 JavaScript 示例代码。

如果你的游戏需要,玩家数据可以从 CloudScript 访问。

有关使用 CloudScript 的更多信息,请参阅 [CloudScript 快速入门](/services/playfab/live-service-management/service-gateway/automation/cloudscript/quickstart)。

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

## CloudScript 代码示例

必须小心确保 CloudScript 中服务器 API 调用的安全性。以下代码演示了如何安全地从 CloudScript 修改一段只读的玩家数据。

```javascript theme={null}
function IncrementReadOnlyUserData(args) {
  var playerData = server.GetUserInternalData({
        PlayFabId: currentPlayerId,
        Keys: ["ReadOnlyTest"]
  });

  var prevCount = "0";
  var nextCount = "1";
  try {
    prevCount = playerData.Data["ReadOnlyTest"].Value;
    var prevInt = parseInt(prevCount, 10);
    if (prevInt != prevInt) {
      prevInt = 0;
      nextCount = (prevInt + 1).toString();
    }
  } catch (e) {
    prevCount = "0";
    nextCount = "0";
  }

  var updateUserDataResult = server.UpdateUserInternalData({
    PlayFabId: currentPlayerId,
    Data:
        {
          "ReadOnlyTest": nextCount
        }
  });
}
```

## C# 代码示例

如 CloudScript 快速入门中所述,你可以从客户端调用以下逻辑。

```csharp theme={null}
public void CloudIncrement() {
    PlayFabClientAPI.ExecuteCloudScript( new ExecuteCloudScriptRequest {
        FunctionName = "IncrementReadOnlyUserData"
    },
    result => Debug.Log("CloudScript call successful"),
    error => {
        Debug.Log("CloudScript call failed");
        Debug.Log(error.GenerateErrorReport());
    });
}
```
