Assets/Scripts/Menu/EndGameManager.cs (view raw)
1using System.IO;
2using System.Runtime.Serialization.Formatters.Binary;
3using UnityEngine;
4using UnityEngine.UI;
5
6public class EndGameManager : MonoBehaviour
7{
8 [Header("UI")]
9 [SerializeField] private GameObject inputPanel = null;
10 [SerializeField] private GameObject highscoresPanel = null;
11 [SerializeField] private Text highscoreName = null;
12 [SerializeField] private Text[] nameObjects = null;
13 [SerializeField] private Text[] scoreObjects = null;
14 [SerializeField] private Text scoreText = null;
15
16 private Leaderboard leaderboard;
17 private int userScore;
18 const int maxRecordsNumber = 4;
19
20 void Start(){
21 GameMaster gm = GameMaster.Instance;
22 userScore = gm.gold;
23 string timeString = gm.GetTimerString();
24 //TODO: set text
25 scoreText.text = "You finished the game in " + timeString + "\nand you collected " + userScore + "g";
26 }
27
28 public void saveHighScore()
29 {
30 inputPanel.SetActive(false);
31
32 BinaryFormatter bf = new BinaryFormatter();
33 FileStream file;
34 //check if leaderboard file exists
35 if (File.Exists(Application.persistentDataPath + "/leaderboard.bin"))
36 {
37
38 file = File.Open(Application.persistentDataPath + "/leaderboard.bin", FileMode.Open);
39 leaderboard = (Leaderboard) bf.Deserialize(file);
40 file.Close();
41 } else {
42 leaderboard = new Leaderboard(maxRecordsNumber);
43 }
44
45 //add new record
46 leaderboard.AddRecord(new Record(highscoreName.text, userScore));
47 file = File.Create(Application.persistentDataPath + "/leaderboard.bin");
48 bf.Serialize(file, leaderboard);
49 file.Close();
50
51 //show records list
52 int i = 0;
53 foreach (Record record in leaderboard.Records)
54 {
55 nameObjects[i].enabled = true;
56 nameObjects[i].text = (i + 1) + ". " + record.Name;
57 scoreObjects[i].enabled = true;
58 scoreObjects[i].text = record.ScoreToString();
59 i++;
60 }
61 for(; i < maxRecordsNumber; i++)
62 {
63 nameObjects[i].enabled = false;
64 scoreObjects[i].enabled = false;
65 }
66
67 highscoresPanel.SetActive(true);
68 }
69
70 public void BackToMainMenu()
71 {
72 UnityEngine.SceneManagement.SceneManager.LoadScene("Menu");
73 }
74}