using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.Events; public class DynamicLeaderboard : MonoBehaviour, ITextChangable { private ScoreController _scoreController; public UnityEvent OnTextChange => _OnTextChange; private UnityEvent _OnTextChange = new UnityEvent(); [SerializeField] private RectTransform _content; [SerializeField] private LeaderboardEntry _leaderboardEntryPrefab; private List _entries = new List(); [SerializeField] private int _abovePlayersCount = 6; [SerializeField] private int _totalPlayersCount = 10; private void Awake() { _scoreController = FindObjectOfType(); } private void OnEnable() { _scoreController.OnScoreChange += OnScoreChange; } private void OnDisable() { _scoreController.OnScoreChange -= OnScoreChange; } private void OnScoreChange(float value) { Debug.Log("Refactor leaderboard"); Debug.Log($"New player {value}"); UpdateLeaderboard(); } [ContextMenu("Debug Update LB")] private void UpdateLeaderboard() { _entries.ForEach(x => Destroy(x.gameObject)); _entries.Clear(); _entries = new List(); var sortedList = PlayerSetup.Instance.AllPlayers.OrderByDescending(x => x.Score).ToList(); int indexOfOutPlayer = sortedList.IndexOf(PlayerSetup.Instance.CurrentPlayer); //int startIndex = Mathf.Clamp(indexOfOutPlayer - _abovePlayersCount, 0, sortedList.Count); //int lastIndex = Mathf.Clamp(indexOfOutPlayer + 3, 0, sortedList.Count); int tmpCounter = 0; for (int i = 0; i < sortedList.Count && tmpCounter <= 9; i++) { if (i >= 5 && i < indexOfOutPlayer) { continue; } tmpCounter++; var newEntry = Instantiate(_leaderboardEntryPrefab, _content); _entries.Add(newEntry); newEntry.Init(sortedList[i], i, sortedList[i] == PlayerSetup.Instance.CurrentPlayer); } _OnTextChange?.Invoke(indexOfOutPlayer + 1); } }