rabidus-test/Assets/Scripts/DynamicLeaderboard.cs

83 lines
2.2 KiB
C#
Raw Permalink Normal View History

2023-08-22 15:41:12 +03:00
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>();
2023-10-05 17:56:59 +03:00
var sortedList = PlayerSetup.Instance.AllPlayers.OrderByDescending(x => x.Score).ToList();
2023-08-22 15:41:12 +03:00
int indexOfOutPlayer = sortedList.IndexOf(PlayerSetup.Instance.CurrentPlayer);
2023-10-02 19:12:35 +03:00
//int startIndex = Mathf.Clamp(indexOfOutPlayer - _abovePlayersCount, 0, sortedList.Count);
//int lastIndex = Mathf.Clamp(indexOfOutPlayer + 3, 0, sortedList.Count);
2023-08-22 15:41:12 +03:00
2023-10-02 19:12:35 +03:00
int tmpCounter = 0;
for (int i = 0; i < sortedList.Count && tmpCounter <= 9; i++)
2023-08-22 15:41:12 +03:00
{
2023-10-02 19:12:35 +03:00
if (i >= 5 && i < indexOfOutPlayer)
{
continue;
}
tmpCounter++;
2023-08-22 15:41:12 +03:00
var newEntry = Instantiate(_leaderboardEntryPrefab, _content);
_entries.Add(newEntry);
2023-10-02 19:12:35 +03:00
newEntry.Init(sortedList[i], i, sortedList[i] == PlayerSetup.Instance.CurrentPlayer);
2023-08-22 15:41:12 +03:00
}
_OnTextChange?.Invoke(indexOfOutPlayer + 1);
}
}