creative-jam-20/Assets/Scripts/HighScoreManager.cs
2022-05-15 17:03:16 -04:00

88 lines
3.0 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class HighScoreManager : MonoBehaviour
{
private Transform entryContainer;
private Transform entryTemplate;
private List<HighScoreEntry> highScoreEntryList;
private List<Transform> highScoreEntryTransformList;
[SerializeField] GameManager gameManager;
[SerializeField] TimeController timeController;
//To add new score: AddHighScoreEntry(10000, "60");
private void Awake()
{
if (SceneManager.GetActiveScene().name.Equals("HighScores"))
{
LoadScores();
}
}
private void LoadScores()
{
entryContainer = transform.Find("EntryContainer");
entryTemplate = entryContainer.Find("EntryTemplate");
entryTemplate.gameObject.SetActive(false);
string jsonString = PlayerPrefs.GetString("highscoreTable");
HighScores highScores = JsonUtility.FromJson<HighScores>(jsonString);
highScoreEntryList = highScores.highscoreEntryList;
highScoreEntryList.Sort((s2, s1) => s1.score.CompareTo(s2.score));
highScoreEntryList = highScoreEntryList.GetRange(0, Mathf.Min(highScores.highscoreEntryList.Count, 10));
highScoreEntryTransformList = new List<Transform>();
foreach (HighScoreEntry highScoreEntry in highScoreEntryList)
{
CreateHighScoreEntryTransform(highScoreEntry, entryContainer, highScoreEntryTransformList);
}
}
private void CreateHighScoreEntryTransform(HighScoreEntry entry, Transform container, List<Transform> transformList)
{
float templateHeight = 50f;
Transform entryTransform = Instantiate(entryTemplate, container);
RectTransform entryRectTransform = entryTransform.GetComponent<RectTransform>();
entryRectTransform.anchoredPosition = new Vector2(0, -templateHeight * transformList.Count);
entryTransform.gameObject.SetActive(true);
entryTransform.Find("Rank").GetComponent<Text>().text = $"{transformList.Count + 1}";
entryTransform.Find("Score").GetComponent<Text>().text = $"{entry.score}";
entryTransform.Find("Time").GetComponent<Text>().text = entry.time;
transformList.Add(entryTransform);
}
public void AddHighScoreEntry(int score, string time)
{
HighScoreEntry highScoreEntry = new HighScoreEntry { score = score, time = time };
string jsonString = PlayerPrefs.GetString("highscoreTable");
HighScores highScores = JsonUtility.FromJson<HighScores>(jsonString);
highScores.highscoreEntryList.Add(highScoreEntry);
string json = JsonUtility.ToJson(highScores);
PlayerPrefs.SetString("highscoreTable", json);
PlayerPrefs.Save();
}
private class HighScores
{
public List<HighScoreEntry> highscoreEntryList;
}
[System.Serializable]
private class HighScoreEntry
{
public int score;
public string time;
}
}