기술 자료

지원

Cloud Code

Cloud Code

크로스 플레이어 데이터와 상호 작용

Access and modify data for multiple players simultaneously with Cloud Code scripts.
읽는 시간 3분최근 업데이트: 12시간 전

Cloud Code 스크립트를 사용하면 여러 플레이어의 데이터에 한 번에 액세스하여 이를 수정할 수 있습니다. 이를 통해 다음과 같은 다양한 사용 사례를 활용할 수 있습니다.
  • Cloud Save에서 여러 플레이어의 플레이어 데이터를 한 번에 업데이트합니다.
  • 여러 플레이어의 Economy 잔액을 한 번에 업데이트합니다.

플레이어 ID 검색

여러 플레이어와 상호 작용하려면 먼저 UGS 서비스를 호출하여 플레이어 ID를 검색해야 합니다. Cloud Code JavaScript SDK를 사용하면 플레이어 ID를 가져올 수 있습니다. 자세한 내용은 Cloud Code JavaScript SDK를 참고하십시오. 서비스의 REST API를 직접 사용해도 됩니다. 플레이어 ID를 가져오는 데 사용할 수 있는 서비스로는 Leaderboards, Lobby, Friends 등이 있습니다.

Leaderboards 사용

먼저 리더보드를 생성해야 합니다. 예를 들어 리더보드에서 상위 플레이어 5명을 검색하고 이들의 ID를 저장할 수 있습니다. 아래 스크립트는 리더보드 ID를 사용하여 상위 플레이어 5명의 점수 목록을 반환합니다.

JavaScript

const { LeaderboardsApi } = require("@unity-services/leaderboards-1.1");module.exports = async ({ params, context, logger }) => { const leaderboardsApi = new LeaderboardsApi(context); let result; try { result = await leaderboardsApi.getLeaderboardScores(context.projectId, params.leaderboardId, 0, 5); return result.data.results; } catch (err) { logger.error("Failed to retrieve players from the leaderboard", {"error.message": err.message}, {"leaderboardId" : params.leaderboardId}); throw err; }};// Uncomment the code below to enable the inline parameter definition// - Requires Cloud Code JS dev environment setup with NodeJS (https://docs.unity3d.com/Packages/com.unity.services.cloudcode@latest/index.html?subfolder=/manual/Authoring/javascript_project.html)//// module.exports.params = {// leaderboardId: { type: "String", required: true },// };
응답의 예시는 다음과 같습니다.
{ "output": [ { "playerId": "wYI5NW5gEVvR3PBmYXEzFS1JvSz3", "playerName": "IncredibleGleamingPelican#3", "rank": 0, "score": 44.0 }, { "playerId": "ryuAA3ZX23aRHN5ZJClC1Z5BrpVb", "playerName": "EffectiveBindingBlackberry#9", "rank": 1, "score": 1.0 } ]}

Lobby 사용

먼저 로비를 생성해야 합니다. 현재 로비에 있는 플레이어의 목록을 검색하고 이들의 ID를 사용하여 데이터와 상호 작용할 수 있습니다. 이 스크립트는 로비 ID를 파라미터로 사용합니다.

JavaScript

const { LobbyApi } = require("@unity-services/lobby-1.2");module.exports = async ({ params, context, logger }) => { const lobbyApi = new LobbyApi(context); try { // Get and return the lobby. const getResponse = await lobbyApi.getLobby(params.lobbyId, "cloud-code"); return getResponse.data.players; } catch (err) { logger.error("Failed to retrieve players from the Lobby", {"error.message": err.message}, {"lobbyId" : params.lobbyId}); throw err; }};// Uncomment the code below to enable the inline parameter definition// - Requires Cloud Code JS dev environment setup with NodeJS (https://docs.unity3d.com/Packages/com.unity.services.cloudcode@latest/index.html?subfolder=/manual/Authoring/javascript_project.html)//// module.exports.params = {// lobbyId: { type: "String", required: true },// };
응답의 예시는 다음과 같습니다.
{ "output": [ { "allocationId": null, "connectionInfo": null, "data": null, "id": "Z96pNb4wfgdaMLqMQfWpwXEclaRR", "joined": "2023-09-08T11:02:18.13Z", "lastUpdated": "2023-09-08T11:02:18.13Z" } ]}

Friends 사용

Friends를 사용하려면 관계를 생성해야 합니다. 자세한 내용은 Friends 기술 자료를 참고하십시오. 그러면 플레이어의 친구 목록을 검색하고 해당하는 친구의 ID를 사용하여 데이터와 상호 작용할 수 있습니다. 아래 샘플은 플레이어가 친구 요청을 보낸 대상의 플레이어 ID 목록을 검색하는 방법을 보여 줍니다.

선택 사항 - 친구 요청 전송

헬퍼 스크립트를 사용하여 플레이어에게 친구 요청을 보낼 수 있습니다. 해당 스크립트는 플레이어 ID를 파라미터로 사용합니다. Unity Cloud Dashboard에서 이 샘플을 테스트하려면 2개의 다른 브라우저 탭에서 2명의 서로 다른 플레이어로 인증된 상태로 스크립트를 실행합니다. 한 탭에서 첫 번째 플레이어 ID로 스크립트를 실행하고, 다른 탭에서 두 번째 플레이어 ID로 스크립트를 실행합니다.
JavaScript
const { RelationshipsApi } = require("@unity-services/friends-1.0");module.exports = async ({ params, context, logger }) => { const relationshipsApi = new RelationshipsApi({ accessToken: context.accessToken }); try { const payload = { type: "FRIEND_REQUEST", members: [{ id: params.playerId }] }; const createRes = await relationshipsApi.createRelationship(true, true, payload); logger.info(`New relationship initiated: ${JSON.stringify(createRes.data)}`) } catch (err) { // The call will fail if the friend request has already been sent logger.error("Error while sending a friend request", { "error.message": err.message }); } try { const list = await relationshipsApi.getRelationships(10, 0, true, true, ["FRIEND_REQUEST", "FRIEND"]); logger.info(`Retrieved relationships: ${JSON.stringify(list.data)}`) } catch (err) { logger.error("Error while retrieving relationships", { "error.message": err.message }); }}// Uncomment the code below to enable the inline parameter definition// - Requires Cloud Code JS dev environment setup with NodeJS (https://docs.unity3d.com/Packages/com.unity.services.cloudcode@latest/index.html?subfolder=/manual/Authoring/javascript_project.html)//// module.exports.params = {// playerId: { type: "String", required: true },// };

친구 목록 검색

아래 스크립트에서는 플레이어가 친구 요청을 보낸 대상의 플레이어 ID 목록을 검색합니다.
JavaScript
const { RelationshipsApi } = require("@unity-services/friends-1.0");module.exports = async ({ params, context, logger }) => { const relationshipsApi = new RelationshipsApi({ accessToken: context.accessToken }); try { const list = await relationshipsApi.getRelationships(10, 0, true, true, ["FRIEND_REQUEST", "FRIEND"]); logger.info(`Retrieved relationships: ${JSON.stringify(list.data)}`) return list.data[0].members; } catch (err) { logger.error("Error while retrieving relationships", { "error.message": err.message }); }}
응답의 예시는 다음과 같습니다.
{ "output": [ { "created": "2023-09-18T14:46:34.74Z", "expires": null, "id": "5774e898-a078-4f92-9f0a-4c9beeb6d1bb", "members": [ { "id": "0gvQingjjBwpZhkUJfeoKnFUkD4T" } ], "type": "FRIEND_REQUEST" } ]}

플레이어 데이터와 상호 작용

플레이어 ID 목록이 있으면 이를 사용하여 UGS 서비스를 통해 플레이어 데이터를 업데이트할 수 있습니다. 아래 샘플은 Cloud SaveEconomy 서비스를 사용하여 플레이어 데이터와 상호 작용하는 방법을 보여 줍니다.

Cloud Code로 인증

크로스 플레이어 데이터와 상호 작용하려면 Cloud Code로 인증해야 합니다. 클라이언트 생성 시
accessToken
대신
serviceToken
을 사용하여 이 작업을 수행할 수 있습니다.
const cloudSaveApi = new DataApi(context);
서비스 및 액세스 토큰 지원에서
ServiceToken
을 지원하는 서비스 목록을 확인하십시오.

Cloud Save를 사용하여 상위 플레이어 5명의 데이터 업데이트

플레이어 데이터와 상호 작용하는 한 가지 방법은 Cloud Save에 플레이어 ID 목록을 전달하는 것입니다. 샘플의 스크립트는 리더보드 ID를 파라미터로 사용합니다. 아래 샘플은 리더보드에서 검색한 상위 플레이어 5명에 대해 Cloud Save에서 값을 설정하는 방법을 보여 줍니다. 다음 단계를 따라 샘플을 사용합니다.
  1. Leaderboards 서비스를 사용하여 리더보드를 생성합니다.
  2. 리더보드에 일부 플레이어의 점수를 제공합니다.
새 스크립트를 생성하고 다음 코드를 추가합니다.

JavaScript

const { LeaderboardsApi } = require("@unity-services/leaderboards-1.1");const { DataApi } = require("@unity-services/cloud-save-1.4");module.exports = async ({ params, context, logger }) => { const leaderboardsApi = new LeaderboardsApi(context); const cloudSaveApi = new DataApi(context); let result; try { result = await leaderboardsApi.getLeaderboardScores(context.projectId, params.leaderboardId, 0, 5); } catch (err) { logger.error("Failed to retrieve players from the leaderboard", {"error.message": err.message}, {"leaderboardId" : params.leaderboardId}); throw err; } if (result.len != 0) { // Set Cloud Save data for every player const promises = result.data.results.map(async (score) => { try { await cloudSaveApi.setItem(context.projectId, score.playerId, { key: "ReachedTop5", value: true, }); } catch (err) { logger.error("Failed to update Cloud Save data", {"error.message": err.message}, {"affectedPlayerId" : score.playerId}); return; } }); await Promise.all(promises); }};// Uncomment the code below to enable the inline parameter definition// - Requires Cloud Code JS dev environment setup with NodeJS (https://docs.unity3d.com/Packages/com.unity.services.cloudcode@latest/index.html?subfolder=/manual/Authoring/javascript_project.html)//// module.exports.params = {// leaderboardId: { type: "String", required: true },// };
이 스크립트는 리더보드에 있는 모든 플레이어에 대한 키-값 페어를 설정합니다. 이를 확인하려면 Unity Cloud Dashboard에서 Player Management 서비스로 이동하여 상위 플레이어의 Cloud Save 데이터를 검사합니다.

Economy를 사용하여 로비에 있는 모든 플레이어에게 보상 제공

플레이어 잔액과 상호 작용하기 위해 Economy API에 플레이어 ID 목록을 전달할 수 있습니다. 아래 샘플은 로비에서 검색된 플레이어 목록의 재화 잔액을 늘리는 방법을 보여 줍니다. 모듈 함수는 로비 ID, 재화 ID, 잔액 증가량을 파라미터로 사용합니다. 다음 단계를 따라 샘플을 사용합니다.
  1. Lobby 서비스를 사용하여 로비를 생성합니다.
  2. 로비에 플레이어를 배치합니다.
  3. Economy 서비스에서 재화를 생성하고 퍼블리시합니다.
새 스크립트를 생성하고 다음 코드를 추가합니다.

JavaScript

const { LobbyApi } = require("@unity-services/lobby-1.2");const { CurrenciesApi, ConfigurationApi } = require("@unity-services/economy-2.4");module.exports = async ({ params, context, logger }) => { const lobbyApi = new LobbyApi(context); let result; try { // Get and return the lobby. result = await lobbyApi.getLobby(params.lobbyId, "cloud-code"); } catch (err) { logger.error("Failed to retrieve players from the Lobby", {"error.message": err.message}, {"lobbyId" : params.lobbyId}); throw err; } const currenciesApi = new CurrenciesApi(context); const configApi = new ConfigurationApi(context); if (result.len != 0) { // Reward currency to every player const promises = result.data.players.map(async (player) => { try { // Retrieve the player config to get the configAssignmentHash. // This is needed to ensure the currency is synced var config = await configApi.getPlayerConfiguration({ playerId: player.id, projectId: context.projectId, }); await currenciesApi.incrementPlayerCurrencyBalance({ currencyId: params.currencyId, playerId: player.id, projectId: context.projectId, configAssignmentHash: config.data.metadata.configAssignmentHash, currencyModifyBalanceRequest: { amount: params.amount } }); } catch (err) { logger.error("Failed to increment currency", {"error.message": err.message}, {"currencyId" : params.currencyId}); throw err; } }); await Promise.all(promises); }};// Uncomment the code below to enable the inline parameter definition// - Requires Cloud Code JS dev environment setup with NodeJS (https://docs.unity3d.com/Packages/com.unity.services.cloudcode@latest/index.html?subfolder=/manual/Authoring/javascript_project.html)//// module.exports.params = {// lobbyId: { type: "String", required: true },// currencyId: { type: "String", required: true },// amount: { type: "Numeric", required: true },// };
이 스크립트는 로비에 있는 모든 플레이어의 재화 잔액을 증가시킵니다. 이를 확인하려면 Unity Cloud Dashboard에서 Player Management 서비스로 이동하여 플레이어의 잔액을 검사합니다.