크로스 플레이어 데이터와 상호 작용
Access and modify data for multiple players at once with Cloud Code modules.
읽는 시간 3분최근 업데이트: 12시간 전
Cloud Code 모듈을 사용하면 여러 플레이어의 데이터에 한 번에 액세스하여 이를 수정할 수 있습니다. 이를 통해 다음과 같은 다양한 사용 사례를 활용할 수 있습니다.
- Cloud Save에서 여러 플레이어의 플레이어 데이터를 한 번에 업데이트합니다.
- 여러 플레이어에게 한 번에 푸시 알림을 보냅니다.
- 여러 플레이어의 Economy 잔액을 한 번에 업데이트합니다.
플레이어 ID 검색
여러 플레이어와 상호 작용하려면 먼저 UGS 서비스를 호출하여 플레이어 ID를 검색해야 합니다.Com.Unity.Services.CloudCode.ApisLeaderboards 사용
먼저 리더보드를 생성해야 합니다. 예를 들어 리더보드에서 상위 플레이어 5명을 검색하고 이들의 ID를 저장할 수 있습니다. 아래 모듈은 리더보드 ID를 사용하여 상위 플레이어 5명의 점수 목록을 반환합니다.using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Logging;using Unity.Services.CloudCode.Apis;using Unity.Services.CloudCode.Core;using Unity.Services.CloudCode.Shared;using Unity.Services.Leaderboards.Model;namespace CrossPlayerData;public class CrossPlayerData{ private readonly ILogger<CrossPlayerData> _logger; public CrossPlayerData(ILogger<CrossPlayerData> logger) { _logger = logger; } [CloudCodeFunction("GetTopPlayers")] public async Task<List<LeaderboardEntry>> GetTopPlayers(IExecutionContext ctx, IGameApiClient gameApiClient, string leaderboardId) { ApiResponse<LeaderboardScoresPage> response; try { response = await gameApiClient.Leaderboards.GetLeaderboardScoresAsync(ctx, ctx.ServiceToken, new Guid(ctx.ProjectId), leaderboardId, null, 5); return response.Data.Results; } catch (ApiException e) { _logger.LogError("Failed to get top players for leaderboard: {LeaderboardId}. Error: {Error}", leaderboardId, e.Message); throw new Exception($"Failed to get top players for leaderboard: {leaderboardId}. Error: {e.Message}"); } } public class ModuleConfig : ICloudCodeSetup { public void Setup(ICloudCodeConfig config) { config.Dependencies.AddSingleton(GameApiClient.Create()); } }}
GetTopPlayers{ "output": [ { "playerId": "wYI5NW5gEVvR3PBmYXEzFS1JvSz3", "playerName": "IncredibleGleamingPelican#3", "rank": 0, "score": 44.0 }, { "playerId": "ryuAA3ZX23aRHN5ZJClC1Z5BrpVb", "playerName": "EffectiveBindingBlackberry#9", "rank": 1, "score": 1.0 } ]}
Lobby 사용
먼저 로비를 생성해야 합니다. 현재 로비에 있는 플레이어의 목록을 검색하고 이들의 ID를 사용하여 데이터와 상호 작용할 수 있습니다.using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Logging;using Unity.Services.CloudCode.Apis;using Unity.Services.CloudCode.Core;using Unity.Services.CloudCode.Shared;using Unity.Services.Lobby.Model;namespace CrossPlayerData;public class CrossPlayerData{ private readonly ILogger<CrossPlayerData> _logger; public CrossPlayerData(ILogger<CrossPlayerData> logger) { _logger = logger; } [CloudCodeFunction("GetLobbyPlayers")] public async Task<List<Player>> GetLobby(IExecutionContext ctx, IGameApiClient gameApiClient, string lobbyId) { ApiResponse<Lobby> response; try { response = await gameApiClient.Lobby.GetLobbyAsync(ctx, ctx.ServiceToken, lobbyId, "cloud-code"); return response.Data.Players; } catch (ApiException e) { _logger.LogError("Failed to get players from lobby: {LobbyId}. Error: {Error}", lobbyId, e.Message); throw new Exception ($"Failed to get players from lobby: {lobbyId}. Error: {e.Message}"); } } public class ModuleConfig : ICloudCodeSetup { public void Setup(ICloudCodeConfig config) { config.Dependencies.AddSingleton(GameApiClient.Create()); } }}
GetLobbyPlayers{ "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 목록을 검색하는 방법을 보여 줍니다.
using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Logging;using Unity.Services.CloudCode.Apis;using Unity.Services.CloudCode.Core;using Unity.Services.Friends.Model;namespace CrossPlayerData;public class CrossPlayerData{ private readonly ILogger<CrossPlayerData> _logger; public CrossPlayerData(IExecutionContext ctx, ILogger<CrossPlayerData> logger) { _logger = logger; } [CloudCodeFunction("SendFriendRequest")] public async Task SendFriendRequest(IExecutionContext ctx, IGameApiClient gameApiClient, string playerId) { try { await gameApiClient.FriendsRelationshipsApi.CreateRelationshipAsync( ctx, ctx.AccessToken, false, false, new AddRelationshipRequest(RelationshipType.FRIENDREQUEST, new List<MemberIdentity> { new(id : playerId) })); } catch (Exception e) { _logger.LogError("Failed to send a friend request to playerId: {playerId}. Error: {Error}", playerId, e.Message); throw new Exception("Failed to send a friend request to playerId: " + playerId + ". Error: " + e.Message); } } [CloudCodeFunction("GetRelationships")] public async Task<List<Relationship>> GetRelationships(IExecutionContext ctx, IGameApiClient gameApiClient) { try { var res = await gameApiClient.FriendsRelationshipsApi.GetRelationshipsAsync(ctx, ctx.AccessToken, 10, 0, false, false); return res.Data; } catch (Exception e) { _logger.LogError("Failed to get relationships for playerId: {playerId}. Error: {Error}", ctx.PlayerId, e.Message); throw new Exception("Failed to get relationships for playerId: " + ctx.PlayerId + ". Error: " + e.Message); } } public class ModuleConfig : ICloudCodeSetup { public void Setup(ICloudCodeConfig config) { config.Dependencies.AddSingleton(GameApiClient.Create()); } }}
GetRelationships{ "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 Save와 Economy 서비스를 사용하여 플레이어 데이터와 상호 작용하는 방법을 보여 줍니다.Cloud Code로 인증
크로스 플레이어 데이터와 상호 작용하려면 Cloud Code로 인증해야 합니다. Cloud Code로 인증하려면 모듈 함수에AccessTokenServiceToken자세한 내용은 인증을 참고하고 서비스 및 액세스 토큰 지원에서await gameApiClient.CloudSaveData.SetItemAsync(ctx, ctx.ServiceToken, ctx.ProjectId, player.PlayerId, new SetItemBody("ReachedTop5", true));
ServiceTokenCloud Save를 사용하여 상위 플레이어 5명의 데이터 업데이트
플레이어 데이터와 상호 작용하는 한 가지 방법은 Cloud Save에 플레이어 ID 목록을 전달하는 것입니다. 샘플의 모듈 함수는 리더보드 ID를 파라미터로 사용합니다. 아래 샘플은 리더보드에서 검색된 상위 플레이어 5명의 목록에 따라 상위 5위에 도달한 플레이어의 값을 Cloud Save에 기록하는 방법을 보여 줍니다. 다음 단계를 따라 샘플을 사용합니다.- Leaderboards 서비스를 사용하여 리더보드를 생성합니다.
- 리더보드에 일부 플레이어의 점수를 제공합니다.
using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Logging;using Unity.Services.CloudCode.Apis;using Unity.Services.CloudCode.Core;using Unity.Services.CloudCode.Shared;using Unity.Services.CloudSave.Model;using Unity.Services.Leaderboards.Model;namespace CrossPlayerData;public class CrossPlayerData{ private readonly ILogger<CrossPlayerData> _logger; public CrossPlayerData(ILogger<CrossPlayerData> logger) { _logger = logger; } [CloudCodeFunction("GetTopPlayers")] public async Task<List<LeaderboardEntry>> GetTopPlayers(IExecutionContext ctx, IGameApiClient gameApiClient, string leaderboardId) { ApiResponse<LeaderboardScoresPage> response; try { response = await gameApiClient.Leaderboards.GetLeaderboardScoresAsync(ctx, ctx.ServiceToken, new Guid(ctx.ProjectId), leaderboardId, null, 5); return response.Data.Results; } catch (ApiException e) { _logger.LogError("Failed to get top players for leaderboard: {LeaderboardId}. Error: {Error}", leaderboardId, e.Message); throw new Exception($"Failed to get top players for leaderboard: {leaderboardId}. Error: {e.Message}"); } } [CloudCodeFunction("UpdateTopPlayerData")] public async Task UpdateTopPlayerData(IExecutionContext ctx, IGameApiClient gameApiClient, string leaderboardId) { var players = GetTopPlayers(ctx, gameApiClient, leaderboardId); foreach (var player in players.Result) { try { await gameApiClient.CloudSaveData.SetItemAsync(ctx, ctx.ServiceToken, ctx.ProjectId, player.PlayerId, new SetItemBody("ReachedTop5", true)); _logger.LogInformation("Updated data for playerId {playerId}", player.PlayerId); } catch (Exception e) { _logger.LogError("Failed to update data for playerId {playerId}. Error: {Error}", player.PlayerId, e.Message); throw new Exception ($"Failed to update data for playerId: {player.PlayerId}. Error: {e.Message}"); } } } public class ModuleConfig : ICloudCodeSetup { public void Setup(ICloudCodeConfig config) { config.Dependencies.AddSingleton(GameApiClient.Create()); } }}
UpdateTopPlayerDataEconomy를 사용하여 로비에 있는 모든 플레이어에게 보상 제공
플레이어 잔액과 상호 작용하기 위해 Economy API에 플레이어 ID 목록을 전달할 수 있습니다. 아래 샘플은 로비에서 검색된 플레이어 목록의 재화 잔액을 늘리는 방법을 보여 줍니다. 모듈 함수는 로비 ID, 재화 ID, 잔액 증가량을 파라미터로 사용합니다. 다음 단계를 따라 샘플을 사용합니다. 새 모듈을 생성하고 다음 코드를 추가합니다.using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Logging;using Unity.Services.CloudCode.Apis;using Unity.Services.CloudCode.Core;using Unity.Services.CloudCode.Shared;using Unity.Services.Economy.Model;using Unity.Services.Lobby.Model;public class CrossPlayerData{ private readonly ILogger<CrossPlayerData> _logger; public CrossPlayerData(ILogger<CrossPlayerData> logger) { _logger = logger; } [CloudCodeFunction("GetLobbyPlayers")] public async Task<List<Player>> GetLobby(IExecutionContext ctx, IGameApiClient gameApiClient, string lobbyId) { ApiResponse<Lobby> response; try { response = await gameApiClient.Lobby.GetLobbyAsync(ctx, ctx.ServiceToken, lobbyId, "cloud-code"); return response.Data.Players; } catch (Exception e) { _logger.LogError("Failed to get players from lobby: {LobbyId}. Error: {Error}", lobbyId, e.Message); throw new Exception ($"Failed to get players from lobby: {lobbyId}. Error: {e.Message}"); } } [CloudCodeFunction("RewardLobbyPlayers")] public async Task RewardLobbyPlayers(IExecutionContext ctx, IGameApiClient gameApiClient, string lobbyId, string currencyId, int amount) { var players = GetLobby(ctx, gameApiClient, lobbyId); foreach (var player in players.Result) { try { await gameApiClient.EconomyCurrencies.IncrementPlayerCurrencyBalanceAsync(ctx, ctx.ServiceToken, ctx.ProjectId, player.Id, currencyId, new CurrencyModifyBalanceRequest(currencyId, amount)); _logger.LogInformation("Incremented balance for playerId {playerId} by {amount}", player.Id, amount); } catch (Exception e) { _logger.LogError("Failed to increment {currencyId} balance for playerId {playerId}. Error: {Error}", currencyId, player.Id, e.Message); throw new Exception($"Failed to increment {currencyId} balance for playerId {player.Id}. Error: {e.Message}"); } } } public class ModuleConfig : ICloudCodeSetup { public void Setup(ICloudCodeConfig config) { config.Dependencies.AddSingleton(GameApiClient.Create()); } }}
RewardLobbyPlayers