LeaderboardManager

mail@pastecode.io avatar
unknown
csharp
15 days ago
1.3 kB
0
Indexable
Never
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class LeaderboardManager : MonoBehaviour
{
    public void SaveScore(string playerName, int score)
    {
        List<ScoreEntry> leaderboard = LoadLeaderboard();
        ScoreEntry newEntry = new ScoreEntry() { playerName = playerName, score = score };
        leaderboard.Add(newEntry);
        leaderboard = leaderboard.OrderBy(entry => entry.score).Take(5).ToList();
        PlayerPrefs.SetString("leaderboard", JsonUtility.ToJson(new ScoreList() { scores = leaderboard }));
        PlayerPrefs.Save();
    }

    public List<ScoreEntry> LoadLeaderboard()
    {
        string json = PlayerPrefs.GetString("leaderboard", "");
        if (string.IsNullOrEmpty(json))
        {
            return new List<ScoreEntry>();
        }
        ScoreList scoreList = JsonUtility.FromJson<ScoreList>(json);
        return scoreList.scores;
    }

    public void DisplayLeaderboard()
    {
        List<ScoreEntry> leaderboard = LoadLeaderboard();
        foreach (var entry in leaderboard)
        {
            Debug.Log("Player: " + entry.playerName + ", Score: " + entry.score);
        }
    }
    public void ClearLeaderboard()
    {
        PlayerPrefs.DeleteKey("leaderboard");
        PlayerPrefs.Save();
    }
}
Leave a Comment