Access Leaderboards via Cloud Code JavaScript Scripts
Refer to code samples that access Leaderboards with the Cloud Code JavaScript Software Development Kit.
Read time 1 minuteLast updated 7 days ago
You can access leaderboards using the Cloud Code JavaScript Leaderboards SDK. The Cloud Code SDK Documentation Portal provides documentation for all the available methods. Consider the example where a player invokes a Cloud Code script. The script submits the player's score, retrieves their entry (including their rank) and retrieves the top scores in the leaderboard. JavaScript:
Admin level access to player-scoped endpoints is also available through Cloud Code. This allows you to update multiple players’ scores, or a player’s score other than the player who invoked the Cloud Code script, from a single Cloud Code script. JavaScript:const { LeaderboardsApi } = require("@unity-services/leaderboards-1.1");module.exports = async ({ params, context, logger }) => { // Retrieve the playerId and accessToken from the context // allows you to ensure requests are scoped to the player // who invoked the Cloud Code script. const { projectId, playerId, accessToken } = context; const { leaderboardId, score } = params; // Initializing the LeaderboardsApi using the accessToken // ensures the requests are made as the player who invoked the // Cloud Code script. const leaderboardsApi = new LeaderboardsApi({ accessToken }); const addScoreResult = await leaderboardsApi.addLeaderboardPlayerScore(projectId, leaderboardId, playerId, { score: score }); const getScoreResult = await leaderboardsApi.getLeaderboardPlayerScore(projectId, leaderboardId, playerId); const getScoresResult = await leaderboardsApi.getLeaderboardScores(projectId, leaderboardId); return { addScoreResultStatus: addScoreResult.status, getScoreResult: getScoreResult.data, getScoresResult: getScoresResult.data };};
const { LeaderboardsApi } = require("@unity-services/leaderboards-1.1");module.exports = async ({ params, context, logger }) => { const { projectId } = context; // The below playerId comes from your input parameters. This can // be any player that you wish. const { leaderboardId, playerId, score } = params; // Initialize the LeaderboardsApi using the context allows // for admin-level access to Leaderboards endpoints. const leaderboardsApi = new LeaderboardsApi(context); const addScoreResult = await leaderboardsApi.addLeaderboardPlayerScore(projectId, leaderboardId, playerId, { score: score }); const getScoreResult = await leaderboardsApi.getLeaderboardPlayerScore(projectId, leaderboardId, playerId); const getScoresResult = await leaderboardsApi.getLeaderboardScores(projectId, leaderboardId); return { addScoreResultStatus: addScoreResult.status, getScoreResult: getScoreResult.data, getScoresResult: getScoresResult.data };};