# Leaderboards

The LeaderboardModule is responsible for managing player scores and ranking players according to their totals. This module provides various functionalities such as setting player scores, getting leaderboard data, and fetching player entries on the leaderboard.

### Using the LeaderboardModule

You can use the module to perform a variety of leaderboard-related operations:

#### Get Leaderboard By ID

Retrieve leaderboard data by providing a `id`to the `GetLeaderboardByIdAsync()` method.

```csharp
public async Task<LeaderboardData> GetLeaderboardByIdAsync(string id)
```

The LeaderboardData contains the following fields:

**LeaderboardData**

* **id** (string): Unique id of the leaderboard.
* **name** (string): Leaderboard name. Is used also to store the localization key for the name.
* **description** (string): Leaderboard description. Is used also to store the localization key for the description.
* **invertSortOrder** (bool): Sorting direction. False implies that places are sorted in descending order, while true means places are sorted in ascending order.
* **decimalOffset** (int): This parameter determines how many digits of the score integer are displayed after the decimal point. The size of the decimal part. For example, with decimalOffset: 2, the number 1234 will be displayed as 12.34.
* **type** (string): The leaderboard type that determines the results unit. Possible values: numeric — Number, time — Time in milliseconds.
* **autoResettable** (bool): Determines whether the leaderboard should automatically reset.
* **resetEveryTimeAtCron** (string): A Cron expression to specify the reset period.
* **rewardsAtReset** (LeaderboardReward\[]): Rewards which will be earned at the reset period.
* **requiredToJoin** (JoinRequirement\[]): A list of requirements that must be met when a user joins a leaderboard. Joining here means adding and setting user scores. Currently, three types are supported. Please see the JoinRequirement description for more information.
* **createdAt** (long): Date and time when the leaderboard was created. This field is automatically populated by the backend.
* **updatedAt** (long): Date and time when the leaderboard was last time updated. This field is automatically populated by the backend.
* **createdBy** (string): User Id who created the leaderboard. This field is automatically populated by the backend.
* **updatedBy** (string): User Id who last time updated the leaderboard. This field is automatically populated by the backend.

**LeaderboardReward**

* **placeFrom** (int): The starting position from which users will earn the reward.
* **placeTo** (int): The ending position up to which users will earn the reward.
* **achievementId** (string): Specifies the reward. It includes various types of rewards like virtual items rewards, currency rewards, etc, linked with a specific [achievement ID](https://playnetwork.gitbook.io/play-sdk-documentation/v0.10.0-dev/sdk-integration-guides/achievements).

**JoinRequirement**

* **type** (string): The type of the join requirement. Currently 3 types are supported:
  * **gamepass** - The user must have a gamepass to join the leaderboard.
  * **item\_by\_id** - A specific virtual item identified by its ID must exist in the user's inventory.
  * **item\_by\_tag** - At least one virtual item in the user's inventory with the provided tag must exist.
* **id** (string): The value for the different type criterias.
  * **gamepass** - The game pass id.
  * **item\_by\_id** - The virtual item id.
  * **item\_by\_tag** - The virtual item tag.

#### Get Leaderboard By Request Name

Retrieve leaderboard data by providing a `requestName` to the `GetLeaderboardByRequestNameAsync()` method.

```csharp
public async Task<LeaderboardData> GetLeaderboardByRequestNameAsync(string requestName)
```

#### Get Leaderboard IDs

Retrieve all leaderboard IDs defined for the current project by calling `GetLeaderboardIdsAsync()` method.

```csharp
using System.Collections.Generic;
using RGN.Modules.Leaderboard;
using UnityEngine;

namespace SomeNamespace
{
    internal sealed class GetLeaderboards
    {
        public async void GetLeaderboardsAsync()
        {
            List<string> leaderboardIds =
                await LeaderboardModule.I.GetLeaderboardIdsAsync();
            for (int i = 0; i < leaderboardIds.Count; ++i)
            {
                Debug.Log("Leaderboard id: " + leaderboardIds[i]);
            }
        }
    }
}
```

#### Set Player Score

Set a player's score on a leaderboard by using the `SetScoreAsync()` method. This method requires `leaderboardId`, `score`, and optionally `extraData` as parameters.

```csharp
using RGN.Modules.Leaderboard;
using UnityEngine;

namespace SomeNamespace
{
    internal sealed class SetPlayerScore
    {
        public async void SetPlayerScoreAsync(string leaderboardId)
        {
            int playerPlace =
                await LeaderboardModule.I.SetScoreAsync(leaderboardId, 42);
            Debug.Log("Player place after setting the score: " +
                playerPlace);
        }
    }
}
```

#### Set Player Score with custom data

Set a player's score on a leaderboard by using the `SetScoreAsync()` method with the optional parameter `extraData`

```csharp
using RGN.Modules.Leaderboard;
using UnityEngine;

namespace SomeNamespace
{
    internal sealed class SetPlayerScoreWithCustomData
    {
        [System.Serializable]
        public struct PlayerData
        {
            public string DisplayName;
            public string Description;
            public int Kills;
            public int Deaths;
        }

        public async void SetPlayerScoreWithCustomDataAsync(
            string leaderboardId,
            PlayerData playerData)
        {
            int playerPlace = await LeaderboardModule.I.SetScoreAsync(
                leaderboardId,
                69,
                JsonUtility.ToJson(playerData));
            Debug.Log("Player place after setting the score: " +
                playerPlace);
        }
    }
}
```

#### Get User Entry

Fetch a player's entry from a specific leaderboard by calling `GetUserEntryAsync()`. This method requires the `leaderboardId` as a parameter.

```csharp
using RGN.Modules.Leaderboard;
using UnityEngine;

namespace SomeNamespace
{
    internal sealed class GetUserEntry
    {
        public async void GetUserEntryAsync(string leaderboardId)
        {
            LeaderboardEntry result = 
                await LeaderboardModule.I.GetUserEntryAsync(leaderboardId);
            var sb = new System.Text.StringBuilder();

            sb.Append("User ID: ").AppendLine(result.userId);
            sb.Append("Score: ").AppendLine(result.score.ToString());
            sb.Append("Formatted Score: ").AppendLine(result.formattedScore);
            sb.Append("Place: ").AppendLine(result.place.ToString());
            sb.Append("Extra Data: ").AppendLine(result.extraData);

            Debug.Log(sb.ToString());
        }
    }
}
```

#### Get Entries

To display user rankings, use the `GetEntriesAsync()` method. This method takes `leaderboardId`, `quantityTop`, `includeUser`, and `quantityAroundUser` as parameters.

```csharp
using System.Collections.Generic;
using RGN.Modules.Leaderboard;
using UnityEngine;

namespace SomeNamespace
{
    internal sealed class GetEntries
    {
        public async void GetEntriesAsync(string leaderboardId)
        {
            List<LeaderboardEntry> results = 
                await LeaderboardModule.I.GetEntriesAsync(
                    leaderboardId,
                    quantityTop: 10,
                    includeUser: true,
                    5);

            for (int i = 0; i < results.Count; ++i)
            {
                LeaderboardEntry result = results[i];
                var sb = new System.Text.StringBuilder();
                sb.Append("User ID: ").AppendLine(result.userId);
                sb.Append("Score: ").AppendLine(result.score.ToString());
                sb.Append("Formatted Score: ").AppendLine(result.formattedScore);
                sb.Append("Place: ").AppendLine(result.place.ToString());
                sb.Append("Extra Data: ").AppendLine(result.extraData);

                Debug.Log(sb.ToString());
            }
        }
    }
}
```

You can create and manage leaderboards by using the developer dashboard or by reaching out to the PLAY team.
