76 lines
2.1 KiB
C#
76 lines
2.1 KiB
C#
|
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<object> OnTextChange => _OnTextChange;
|
||
|
private UnityEvent<object> _OnTextChange = new UnityEvent<object>();
|
||
|
|
||
|
[SerializeField]
|
||
|
private RectTransform _content;
|
||
|
[SerializeField]
|
||
|
private LeaderboardEntry _leaderboardEntryPrefab;
|
||
|
|
||
|
private List<LeaderboardEntry> _entries = new List<LeaderboardEntry>();
|
||
|
|
||
|
[SerializeField]
|
||
|
private int _abovePlayersCount = 6;
|
||
|
[SerializeField]
|
||
|
private int _totalPlayersCount = 10;
|
||
|
|
||
|
|
||
|
private void Awake()
|
||
|
{
|
||
|
_scoreController = FindObjectOfType<ScoreController>();
|
||
|
}
|
||
|
|
||
|
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<LeaderboardEntry>();
|
||
|
Debug.Log("Tst");
|
||
|
|
||
|
var sortedList = PlayerSetup.Instance.PlayerInfo.Players.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(startIndex + _totalPlayersCount, 0, sortedList.Count);
|
||
|
|
||
|
for (int i = startIndex; i < lastIndex; i++)
|
||
|
{
|
||
|
var newEntry = Instantiate(_leaderboardEntryPrefab, _content);
|
||
|
_entries.Add(newEntry);
|
||
|
newEntry.Init(sortedList[i], i, i == indexOfOutPlayer);
|
||
|
}
|
||
|
|
||
|
_OnTextChange?.Invoke(indexOfOutPlayer + 1);
|
||
|
}
|
||
|
}
|