# 面向 Cloud Code 的 Cloud Save 教程

> Use Cloud Code to access, modify, and manage Cloud Save data to achieve server-authoritative gameplay.

面向 Cloud Code 的 Cloud Save SDK 让您可以从 Cloud Code 读写玩家数据、读写游戏数据以及查询数据（如果您已配置索引，使数据可查询）。

请参阅[面向 Cloud Code 的 Cloud Save SDK 文档](https://cloud-code-sdk-documentation.cloud.unity3d.com/cloud-save/)，获取所有可用方法的列表。

## 从 Cloud Code 访问 Cloud Save##authentication

以下是如何通过 Cloud Code 脚本写入玩家数据的示例。

*Javascript*

```js
const _ = require("lodash-4.17");
const {
  DataApi
} = require("@unity-services/cloud-save-1.4");

const NUMBER_OF_SIDES = 6;

module.exports = async ({ params, context, logger }) => {
  const {
	projectId,
	playerId
  } = context;

  const api = new DataApi(context);

  const roll = rollDice(NUMBER_OF_SIDES);

  if (roll > NUMBER_OF_SIDES) {
    // Log an error message with information about the exception
	logger.error("The roll is greater than the number of sides: " + roll);
    // Return an error back to the client
    throw Error("Unable to roll dice!");
  }

  // Return a JSON result to the client
  const result = {
	sides: NUMBER_OF_SIDES,
	roll: roll,
  };

  const setResult = await api.setItem(projectId, playerId, {
	key: "DIE_ROLL",
	value: result
  });
  logger.debug(JSON.stringify(setResult.data));

  return result;
};

// Function outside of the script wrapper
function rollDice(sides) {
  return _.random(1, sides);
}
```

## 跨玩家数据##using-cloud-save-with-cloud-code-modules

通过将另一个玩家的 ID 传递到 Cloud Save SDK，您可以读写其 Cloud Save 数据，从而实现异步玩家多人联网交互。这不可能从客户端内实现，因为客户端只允许用户访问自己的数据。

以下示例展示了如何向同一[大厅](/lobby.md)内的其他玩家提供表扬。样本代码演示了如何访问和修改存储在 Cloud Save 中的其他玩家的数据。`otherPlayerId` 参数标识其他玩家。

*Javascript*

```js
const { DataApi } = require('@unity-services/cloud-save-1.4');

module.exports = async ({ params, context, logger }) => {
  const { projectId } = context;
  const { otherPlayerId } = params;

  // Initialize the cloud save API client
  const cloudSaveAPI = new DataApi(context);

  // Access the save data for the specified player
  const otherPlayerSave = await cloudSaveAPI.getItems(
    projectId,
    otherPlayerId, // or any other player ID
    "likes" // Cloud Code key
  );

  // Assume that player's likes is 0 if the key doesn't exist
  const otherPlayerLikes = otherPlayerSave.data.results[0]?.value || 0;

  // Update the data for the specified player
  cloudSaveAPI.setItem(
    projectId,
    otherPlayerId, { key: "likes", value: otherPlayerLikes + 1 }
  )
};
```

来自玩家的请求应被视为不受信任的输入，因此在接受其他玩家的 ID 作为参数时要小心，如以上示例所示。如果游戏对玩家之间交互的时间或方式有限制（例如，玩家是否可以选择退出多人联网），那么您需要检查脚本中的相关先决条件。

## 用例和示例##use-cloud-save-with-cloud-code-scripts

使用 Cloud Code 脚本探索 Cloud Save SDK 的其他用例和示例。

\| 主题 | 描述 | |-|-| | [任务系统](/cloud-code/modules/use-cases/quest-system.md) | 服务器授权/反作弊任务系统。*Cloud Code 模块 (C#)* | | [可兑换优惠券](/cloud-code/scripts/use-cases/redeemable-coupons.md) | 为玩家提供游戏内奖励。*Cloud Code 脚本 (JavaScript)* | | [服务器时间反作弊](/cloud-code/scripts/use-cases/server-time-anti-cheat.md) | 实施反作弊系统。*Cloud Code 脚本 (JavaScript)* |
