132 lines
2.8 KiB
C#
132 lines
2.8 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
public class RankSystem : MonoBehaviour
|
|
{
|
|
public static event Action<RankInfo> OnNewRank;
|
|
public List<RankInfo> Ranks;
|
|
private RankInfo currentRank;
|
|
private bool initialized = false;
|
|
|
|
public static RankSystem Instance;
|
|
|
|
public void Initialize()
|
|
{
|
|
if (Ranks == null || Ranks.Count == 0)
|
|
{
|
|
Debug.LogError("Ранги не заданы", this);
|
|
return;
|
|
}
|
|
Instance = this;
|
|
Ranks.Sort();
|
|
currentRank = Ranks[0];
|
|
initialized = true;
|
|
}
|
|
|
|
public void SubscribeOnScore()
|
|
{
|
|
G.Rank = currentRank;
|
|
Refresh(G.ScoreModel);
|
|
G.ScoreModel.OnUpdate += Refresh;
|
|
}
|
|
|
|
public void UnsubscribeOnScore()
|
|
{
|
|
if (G.ScoreModel != null)
|
|
G.ScoreModel.OnUpdate -= Refresh;
|
|
}
|
|
|
|
public void ResetSystem()
|
|
{
|
|
UnsubscribeOnScore();
|
|
Initialize();
|
|
}
|
|
|
|
private void Refresh(ScoreModel model)
|
|
{
|
|
int score = model.Score;
|
|
Refresh(score);
|
|
}
|
|
|
|
private void Refresh(int score)
|
|
{
|
|
RankInfo RankByScore = GetActualRank(score);
|
|
|
|
if (RankByScore != currentRank)
|
|
{
|
|
currentRank = RankByScore;
|
|
G.Rank = currentRank;
|
|
OnNewRank?.Invoke(currentRank);
|
|
}
|
|
}
|
|
|
|
|
|
|
|
private void OnDestroy()
|
|
{
|
|
if (!initialized) return;
|
|
UnsubscribeOnScore();
|
|
}
|
|
|
|
private RankInfo GetActualRank(int score)
|
|
{
|
|
for (int i = Ranks.Count - 1; i >= 0; i--)
|
|
{
|
|
if (score >= Ranks[i].RequiredScore)
|
|
{
|
|
return Ranks[i];
|
|
}
|
|
}
|
|
|
|
return Ranks[0];
|
|
}
|
|
|
|
public int GetActualRankIndex(int score)
|
|
{
|
|
for (int i = Ranks.Count - 1; i >= 0; i--)
|
|
{
|
|
if (score >= Ranks[i].RequiredScore)
|
|
{
|
|
return i;
|
|
}
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
public bool HasNextRank(int score)
|
|
{
|
|
int nextRankIndex = GetActualRankIndex(score) + 1;
|
|
return nextRankIndex < Ranks.Count;
|
|
}
|
|
|
|
public int ScoreToNextRank(int score)
|
|
{
|
|
int currentIndex = GetActualRankIndex(score);
|
|
int nextRankIndex = currentIndex + 1;
|
|
|
|
if (nextRankIndex < Ranks.Count)
|
|
{
|
|
return Ranks[nextRankIndex].RequiredScore - score;
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
|
|
[Serializable]
|
|
public class RankInfo : IComparable<RankInfo>
|
|
{
|
|
public string Name;
|
|
public Sprite Sprite;
|
|
public Sprite SpriteGreen;
|
|
public int RequiredScore;
|
|
|
|
public int CompareTo(RankInfo other)
|
|
{
|
|
if (other == null) return 1;
|
|
return RequiredScore.CompareTo(other.RequiredScore);
|
|
}
|
|
}
|
|
}
|