/// <summary> /// Saving the score /// </summary> public void SaveScore() { // It is just possible to save the data of the current session, // if it is not yet saved if (!scoreYetSaved) { try { // Creating all directories to the endpath, where the score // shall be saved System.IO.Directory.CreateDirectory(pathToScoreFolder); StreamWriter sw = new StreamWriter(pathToScoreFile, false); // Getting the name and score of the current game session String name = nameTextfield.text; int score = (int)player.Score; // Adding the data of the current game-session to the list, which // contains the data of the previous sessions scoreEntries.Add(new ScoreEntry(name, score)); ScoreEntryList entryList = new ScoreEntryList(); entryList.Entries = scoreEntries.ToArray(); // Parsing the list with all game-seesions into a json-String // to write this string into a file. string scoreJSON = JsonConvert.SerializeObject(entryList); sw.Write(scoreJSON); sw.Close(); // Hiding the save button. saveButton.SetActive(false); } catch (Exception e) { Debug.Log("Sorry, but your score could not be saved!"); } } }
/// <summary> /// Reading the data, from the file, of the previous game-sessions /// </summary> public void ReadScore() { try { StreamReader sr = new StreamReader(pathToScoreFile); String content = sr.ReadToEnd(); sr.Close(); // Parsing the data, from the score-file inso a list-object ScoreEntryList scoreEntryList = JsonConvert.DeserializeObject <ScoreEntryList>(content); scoreEntries = new List <ScoreEntry>(scoreEntryList.Entries); // Sorting the scoredata by the score, so that the highscore-points are // listed in descending order scoreEntries.Sort(new ScoreListComparer()); // Building a string from the array-list StringBuilder scoreString = new StringBuilder(); foreach (ScoreEntry scoreEntry in scoreEntries) { scoreString.Append(scoreEntry.Score + " " + scoreEntry.Name + "\n"); } // Visualising the text on the provided text-object highscoreText.text = scoreString.ToString(); } catch (Exception e) { Debug.Log(e.Message); Debug.Log("The score file could not be read!"); } if (scoreEntries == null) { scoreEntries = new List <ScoreEntry>(); } }