using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.Events; using UnityEngine.UI; public class LeaderboardController : MonoBehaviour { private const string DAILY_ID = "DAILY_LB"; private const string GLOBAL_ID = "GLOBAL_LB"; public static LeaderboardController Instance; [SerializeField] private PlayerInfo _dailyPlayerInfo; [SerializeField] private PlayerInfo _globalPlayerInfo; public UnityEvent> OnDailyInit; public UnityEvent> OnGlobalInit; public UnityEvent OnDailyNewRecord; public UnityEvent OnGlobalNewRecord; private void Start() { //yield return new WaitForSeconds(1); InitDailyLeaderboard(); InitGlobalLeaderboard(); } private void InitDailyLeaderboard() { StartCoroutine(InitDailyLeaderboard_Coroutine()); } private void InitGlobalLeaderboard() { StartCoroutine(InitGlobalLeaderboard_Coroutine()); } private IEnumerator InitDailyLeaderboard_Coroutine() { string lastSave = PlayerPrefs.GetString(DAILY_ID, string.Empty); DateTime lastSaveDate; if (DateTime.TryParse(lastSave, out lastSaveDate) && DateTime.Now.Day <= lastSaveDate.Day) { yield return SaveLoadController.Instance.Load(ref _dailyPlayerInfo, DAILY_ID); } else { yield return SaveLoadController.Instance.Save(_dailyPlayerInfo, DAILY_ID); } PlayerPrefs.SetString(DAILY_ID, DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")); Debug.Log("End daily lb init"); RefreshDailyEntries(); yield return null; } private IEnumerator InitGlobalLeaderboard_Coroutine() { if (PlayerPrefs.GetInt(GLOBAL_ID, 0) == 1) { yield return SaveLoadController.Instance.Load(ref _globalPlayerInfo, GLOBAL_ID); } else { yield return SaveLoadController.Instance.Save(_globalPlayerInfo, GLOBAL_ID); } PlayerPrefs.SetInt(GLOBAL_ID, 1); Debug.Log("End global lb init"); RefreshGlobalEntries(); yield return null; } private void RefreshDailyEntries() { _dailyPlayerInfo.Players = _dailyPlayerInfo.Players.OrderByDescending(x => x.Score).ToList(); OnDailyInit?.Invoke(_dailyPlayerInfo.Players); } private void RefreshGlobalEntries() { _globalPlayerInfo.Players = _globalPlayerInfo.Players.OrderByDescending(x => x.Score).ToList(); OnGlobalInit?.Invoke(_globalPlayerInfo.Players); } public void SavePlayerRecord(Player player) { CheckDailyLeaderboard(player); CheckGlobalLeaderboard(player); } private void CheckDailyLeaderboard(Player player) { if (player.Score >= _dailyPlayerInfo.Players.Last().Score) { _dailyPlayerInfo.Players[_dailyPlayerInfo.Players.IndexOf(_dailyPlayerInfo.Players.Last())] = player; RefreshDailyEntries(); OnDailyNewRecord?.Invoke(_dailyPlayerInfo.Players.IndexOf(player)); } } private void CheckGlobalLeaderboard(Player player) { if (player.Score >= _globalPlayerInfo.Players.Last().Score) { _globalPlayerInfo.Players[_globalPlayerInfo.Players.IndexOf(_globalPlayerInfo.Players.Last())] = player; RefreshGlobalEntries(); OnGlobalNewRecord?.Invoke(_globalPlayerInfo.Players.IndexOf(player)); } } }