/// <summary> /// Loads player data /// </summary> public void LoadData() { //DeleteFile (); BinaryFormatter bf = new BinaryFormatter(); //Check whether file exists if (File.Exists(Application.persistentDataPath + filePath)) { Debug.LogWarning("Loading file"); FileStream file = File.Open(Application.persistentDataPath + filePath, FileMode.Open); allLeaders = (LeaderboardData)bf.Deserialize(file); file.Close(); } else { Debug.LogWarning("Created file"); //Create file and parse in faked data FileStream file = File.Open(Application.persistentDataPath + filePath, FileMode.CreateNew); LeaderboardData FakeData = new LeaderboardData(); //Loop through moving down players for (int i = 0; i < 10; i++) { LeaderboardData.LeaderBoardPlayer player = new LeaderboardData.LeaderBoardPlayer(); player.PlayerScore = 0; player.PlayerName = "None"; FakeData.SetLeaderPosition(i, player); } allLeaders = FakeData; bf.Serialize(file, FakeData); file.Close(); } }
/// <summary> /// Saves new player score to file /// </summary> public void Save() { BinaryFormatter bf = new BinaryFormatter(); FileStream file = File.Open(Application.persistentDataPath + filePath, FileMode.Open); int count = 0; //Loop through and add score to leaderboard players if they beat anyone foreach (LeaderboardData.LeaderBoardPlayer n in allLeaders.LeaderboardArray) { if (n.PlayerScore < myScore) { //Loop through moving down players for (int i = 8; i >= count; i--) { //THIS WILL ACTIVATE GARBAGE COLLECTION BC ALWAYS CREATING NEW PLAYER LeaderboardData.LeaderBoardPlayer player = new LeaderboardData.LeaderBoardPlayer(); player.PlayerScore = allLeaders.LeaderboardArray[i].PlayerScore; player.PlayerName = allLeaders.LeaderboardArray[i].PlayerName; allLeaders.SetLeaderPosition(i + 1, player); } //Set new score after moving down losers LeaderboardData.LeaderBoardPlayer me = new LeaderboardData.LeaderBoardPlayer(); me.PlayerScore = myScore; me.PlayerName = myName; allLeaders.SetLeaderPosition(count, me); break; } count++; } //Save data in binary to file bf.Serialize(file, allLeaders); file.Close(); }