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 [SerializeField] private GameObject inputPanel = null;
9 [SerializeField] private GameObject highscoresPanel = null;
10 [SerializeField] private Text highscoreName = null;
11 [SerializeField] private Text[] nameObjects = null;
12 [SerializeField] private Text[] scoreObjects = null;
13 private Leaderboard leaderboard;
14 private int userScore;
15 const int maxRecordsNumber = 4;
16
17 void Start(){
18 userScore = GameMaster.Instance.gold;
19 }
20
21 public void saveHighScore()
22 {
23 inputPanel.SetActive(false);
24
25 BinaryFormatter bf = new BinaryFormatter();
26 FileStream file;
27 //check if leaderboard file exists
28 if (File.Exists(Application.persistentDataPath + "/leaderboard.bin"))
29 {
30
31 file = File.Open(Application.persistentDataPath + "/leaderboard.bin", FileMode.Open);
32 leaderboard = (Leaderboard) bf.Deserialize(file);
33 file.Close();
34 } else {
35 leaderboard = new Leaderboard(maxRecordsNumber);
36 }
37
38 //add new record
39 leaderboard.AddRecord(new Record(highscoreName.text, userScore));
40 file = File.Create(Application.persistentDataPath + "/leaderboard.bin");
41 bf.Serialize(file, leaderboard);
42 file.Close();
43
44 //show records list
45 int i = 0;
46 foreach (Record record in leaderboard.Records)
47 {
48 nameObjects[i].enabled = true;
49 nameObjects[i].text = (i + 1) + ". " + record.Name;
50 scoreObjects[i].enabled = true;
51 scoreObjects[i].text = record.ScoreToString();
52 i++;
53 }
54 for(; i < maxRecordsNumber; i++)
55 {
56 nameObjects[i].enabled = false;
57 scoreObjects[i].enabled = false;
58 }
59
60 highscoresPanel.SetActive(true);
61 }
62
63 public void BackToMainMenu()
64 {
65 UnityEngine.SceneManagement.SceneManager.LoadScene("Menu");
66 }
67}