Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System.Collections;
- using System.Collections.Generic;
- using UnityEngine;
- using System.Linq;
- using System.Text;
- public class HighScoreManager : MonoBehaviour {
- private static readonly string CSV_HIGHSCORE_KEY = "highScores";
- public static void SaveHighscore(int score, string name){
- int insertIndex = 0;
- bool addToEndOfFile = true;
- List<string> highscoreList = LoadHighscores ();
- List<string> tempList = new List<string> ();
- StringBuilder sb = new StringBuilder ();
- //If the highscores contains previous scores
- if (highscoreList.Count != 0) {
- //For each score value in the highscore list
- for (int i = 1; i < highscoreList.Count; i += 2){
- //If score is higher than selected value
- if (int.Parse(highscoreList[i]) < score) {
- //set insert index
- insertIndex = i;
- //set addToEndOfFile to false
- addToEndOfFile = false;
- }
- }
- }
- //If addToEndOfFile is true
- if (addToEndOfFile) {
- //Add score to end of the list
- highscoreList.Add (name);
- highscoreList.Add (score.ToString ());
- } else {
- //Move data over to a temporary list, this is faster than using insert
- for (int i = 0; i < highscoreList.Count; i++) {
- //If the current index is where we have to insert the new score
- if (i == insertIndex) {
- //Insert the player score and name
- tempList.Add (name);
- tempList.Add (score.ToString ());
- }
- //Add the value from the old list to the end of the temp list
- tempList.Add (highscoreList [i]);
- }
- //Set highscoreList to the values of tempList
- highscoreList = tempList;
- }
- //Create a string with all the data from the List, with a comma (',') seperating each array item
- for (int i = 0; i < highscoreList.Count; i++){
- if (i == 0) {
- sb.Append (highscoreList [i]);
- }else{
- sb.Append (",");
- sb.Append (highscoreList [i]);
- }
- }
- //Save the string to player prefs
- SaveToPlayerPrefs(sb.ToString());
- }
- private static void SaveToPlayerPrefs(string csv){
- //Set the playerPrefs value to the input string
- PlayerPrefs.SetString(CSV_HIGHSCORE_KEY, csv);
- }
- public static List <string> LoadHighscores(){
- //If the playerPrefs exists
- if (PlayerPrefs.HasKey (CSV_HIGHSCORE_KEY)) {
- //Get the CSV string from playerPrefs
- string csv = PlayerPrefs.GetString (CSV_HIGHSCORE_KEY);
- //Return a List of strings, seperating the CSV by commas
- return csv.Split (',').ToList ();
- } else {
- //Return blank List
- return new List<string> ();
- }
- }
- public static void ShowHighscores(){
- List<string> hs = LoadHighscores();
- for(int i = 1; i < hs.Count; i += 2){
- Debug.Log(hs[i] + ":" + hs[i + 1]);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement