I need a little bit of help on how can I sort the leaderboard with having a realtime update.
Like highest to lowest score.
(Game is like IO games)
here's the leaderboard entry code
Code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
public class LeaderboardEntry : MonoBehaviour
{
public int id;
public Text placement, playerName, playerScore;
private void Update()
{
UpdateInfo();
}
public void UpdateInfo()
{
placement.text = (id + 1).ToString();
playerName.text = Leaderboard.Instance.pInfo[id].name;
playerScore.text = Leaderboard.Instance.pInfo[id].score.ToString("0");
}
}
Here's the Leaderboard Code itself
Code:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.Networking;
public class Leaderboard : NetworkBehaviour
{
public static Leaderboard Instance;
public List<LeaderboardEntry> entries;
PlayerInfo[] LBoard = new PlayerInfo[5];
public struct PlayerInfo
{
public string name;
public float score;
public PlayerInfo(string name, float score)
{
this.name = name;
this.score = score;
}
}
//make sure that the class name starts with SyncList
public class SyncListInfo : SyncListStruct<PlayerInfo> { }
public SyncListInfo pInfo = new SyncListInfo();
private void Awake()
{
Instance = this;
//Disable all the leaderboard entries
for (int i = 0; i < entries.Count; i++)
entries[i].gameObject.SetActive(false);
}
[Command]
public void CmdAddPlayerInfo(string name, float score)
{
Debug.Log(string.Format("adding info: {0} & {1}", name, score));
pInfo.Add(new PlayerInfo(name, score));
Debug.Log("There are " + pInfo.Count + " elements in the struct list.");
//enable the entry
EnableEntry(pInfo.Count);
//make sure that enable entry is also called on all connected clients
RpcEnableEntry(pInfo.Count);
}
[Command]
public void CmdUpdatePlayerInfo(string name, float score)
{
for(int i = 0; i < pInfo.Count; i++)
{
if(pInfo[i].name == name)
{
pInfo[i] = new PlayerInfo(name, score);
}
Array.Sort(LBoard, (x, y) => x.score.CompareTo(y.score));
Array.Sort(LBoard, delegate (PlayerInfo p1, PlayerInfo p2)
{
return p1.score.CompareTo(p2.score);
});
}
}
[ClientRpc]
void RpcEnableEntry(int count)
{
EnableEntry(count);
}
private void EnableEntry(int count)
{
for (int i = 0; i < count; i++)
{
entries[i].gameObject.SetActive(true);
}
}
}