Photon Unity Leaderboard sorting

1.8k views Asked by At

I am trying to get the scores of the players in multiplayer mode using Photon Unity Networking.

PhotonNetwork.playerList[i].GetScore();

I use the above line to get the scores of all the players in the room currently.

I added the Player Name and Score to a dictionary like this, 1. Player Name as "Key". 2. Player Score as "Value".

for(int i = 0; i < PhotonNetwork.playerList.Length; i++)
{
    if (dict.ContainsKey (PhotonNetwork.playerList[i].name))
    {
        dict[PhotonNetwork.playerList[i].name] = PhotonNetwork.playerList[i].GetScore();
    }
    else
    {
        dict.Add (PhotonNetwork.playerList[i].name, PhotonNetwork.playerList[i].GetScore());
    }
}

After this, I wanted the top 5 scores and the names in descending order. So, I sorted the dictionary and took the top 5 values like this,

foreach(var item in dict.OrderByDescending(r => r.Value).Take(5))
{
    scoreText.text = item.Key +" "+ item.Value;
}

Output required is "The sorted 5 elements in the dictionary" Please help me to find the solution. Thanks.

1

There are 1 answers

0
Виталий Белоусов On

You can just use this line of code:

var sortedPlayerList = (from p in playerList orderby p.GetMyScore() descending select p).ToList();

It will sort an array with descending, and you can show top 5 players like this:

for(int i = 0; i < 5; i++) {
    // show your player's score
}