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

83 lines
2.9 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
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()
{
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));
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);
}
private 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;
}
public void TempGameOver()
{
AddHighScoreEntry((int)gameManager.GetPoints(), timeController.GetTime());
Debug.Log("Added entry");
}
}