Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

setting highscores for multiple levels

Discussion in 'Scripting' started by jbowers74321, Dec 31, 2019.

  1. jbowers74321

    jbowers74321

    Joined:
    Oct 30, 2019
    Posts:
    25
    what is the best way to set a high score for different scenes I have been working on playerprefs and binary formatter for days now I have tried to save the high score on my score text here

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using System.Net;
    4. using UnityEngine;
    5. using UnityEngine.UI;
    6. using UnityEngine.SceneManagement;
    7. using System.Runtime.Serialization.Formatters.Binary;
    8. using System.IO;
    9. using System;
    10.  
    11. public class Score : MonoBehaviour
    12. {
    13.     public float score = 0.0f;
    14.     public float highscore;
    15.     public float difficultyLevel = 1;
    16.     public float maxDifficultyLevel = 10;
    17.     public float scoreToNextLevel = 10;
    18.     public Scene scene;
    19.     public bool isDead = false;
    20.  
    21.     public Text scoreText;
    22.     public DeathMenu deathMenu;
    23.  
    24.     // Start is called before the first frame update
    25.     void Start()
    26.     {
    27.  
    28.     }
    29.  
    30.     // Update is called once per frame
    31.     void Update()
    32.     {
    33.         if (isDead)
    34.             return;
    35.  
    36.         if (score > highscore)
    37.         {
    38.             highscore = score;
    39.             scoreText.text = highscore.ToString(); ;
    40.         }
    41.  
    42.         if (score >= scoreToNextLevel)
    43.             LevelUp();
    44.  
    45.         score += Time.deltaTime * difficultyLevel;
    46.         scoreText.text = ((int)score).ToString();
    47.  
    48.     }
    49.  
    50.     public void AddScore(int addedScorePoints)
    51.     {
    52.         score += addedScorePoints;
    53.     }
    54.  
    55.     void LevelUp()
    56.     {
    57.         if (difficultyLevel == maxDifficultyLevel)
    58.             return;
    59.  
    60.         scoreToNextLevel *= 2;
    61.         difficultyLevel++;
    62.  
    63.         GetComponent<playermotor>().SetSpeed(difficultyLevel);
    64.     }
    65.  
    66.     public void Save()
    67.     {
    68.         if (Directory.Exists(Application.dataPath + "/Save data/(scene.name)/") == false)
    69.             Directory.CreateDirectory(Application.dataPath + "/Save data/(scene.name)/");
    70.         BinaryFormatter bf = new BinaryFormatter();
    71.         FileStream file = File.Create(Application.dataPath + "/Save data/(scene.name)/Score.secure");
    72.         ScoreData data = new ScoreData();
    73.        
    74.         data.highscore = this.highscore;
    75.  
    76.         bf.Serialize(file, data);
    77.         file.Close();
    78.     }
    79.  
    80.     public void OnDeath()
    81.     {
    82.         isDead = true;
    83.         deathMenu.ToggleEndMenu(score);
    84.     }
    85.  
    86.     [Serializable]
    87.     class ScoreData
    88.     {
    89.         public float highscore;
    90.     }
    91. }
    I need it to save a separate high score for each scene which i tried to do with scene.name and I am trying to load the score on my level select screen here

    Code (CSharp):
    1. public class LevelSelect : MonoBehaviour
    2. {
    3.  
    4.     public Text foresthscoreText;
    5.     public Text deserthscoreText;
    6.     public float score;
    7.     public float highscore;
    8.  
    9.     // Start is called before the first frame update
    10.     void Start()
    11.     {
    12.  
    13.     }
    14.  
    15.     public void Load()
    16.     {
    17.         if (File.Exists(Application.dataPath + "/Save data/(scene.name)/Score.secure"))
    18.         {
    19.             BinaryFormatter bf = new BinaryFormatter();
    20.             FileStream file = File.Open(Application.dataPath + "/Save data/(scene.name)/Score.secure", FileMode.Open);
    21.             ScoreData data = (ScoreData)bf.Deserialize(file);
    22.             file.Close();
    23.  
    24.             this.highscore = data.highscore;
    25.             foresthscoreText.text = highscore.ToString();
    26.         }
    27.     }
    I have been searching and trying on my own for days if anyone could help I would really appreciate it
     
  2. adi7b9

    adi7b9

    Joined:
    Feb 22, 2015
    Posts:
    181
    This is a simpler example of the highscore system in a file. You can extend this.
    Code (CSharp):
    1. [Serializable]
    2. public class Score
    3. {
    4.     public string Name { get; set; }
    5.     public int Result { get; set; }
    6. }
    7.  
    8. [Serializable]
    9. public class ScenesHS
    10. {
    11.     public string SceneName { get; set; }
    12.     public int IndexScene { get; set; }
    13.     public List<Score> HS { get; set; }
    14. }
    15.  
    16. public class HighS
    17. {
    18.     List<ScenesHS> scenesHighScores = new List<ScenesHS>();
    19.  
    20.     //only to test my program
    21.     public void PopulateScores()
    22.     {
    23.         string nameDict = "abcdefghijklmn";
    24.         for (int scene = 0; scene < 10; scene++)
    25.         {
    26.             string name = "" + nameDict[scene];
    27.  
    28.             ScenesHS shs = new ScenesHS();
    29.             shs.HS = new List<Score>();
    30.             shs.SceneName = name;
    31.             shs.IndexScene = scene;
    32.  
    33.             for (int highScores = 0; highScores < 5; highScores++)
    34.             {
    35.                 shs.HS.Add(new Score { Name = name + highScores.ToString(), Result = highScores * 5 });
    36.             }
    37.             scenesHighScores.Add(shs);
    38.         }
    39.     }
    40.  
    41.     //from https://docs.microsoft.com/en-us/dotnet/api/system.runtime.serialization.formatters.binary.binaryformatter.deserialize?view=netframework-4.8
    42.     public void Save()
    43.     {
    44.         FileStream fs = new FileStream("DataFile.dat", FileMode.Create);
    45.  
    46.         // Construct a BinaryFormatter and use it to serialize the data to the stream.
    47.         BinaryFormatter formatter = new BinaryFormatter();
    48.         try
    49.         {
    50.             formatter.Serialize(fs, scenesHighScores);
    51.         }
    52.         catch (SerializationException e)
    53.         {
    54.             Console.WriteLine("Failed to serialize. Reason: " + e.Message);
    55.             throw;
    56.         }
    57.         finally
    58.         {
    59.             fs.Close();
    60.         }
    61.     }
    62.  
    63.     //from https://docs.microsoft.com/en-us/dotnet/api/system.runtime.serialization.formatters.binary.binaryformatter.deserialize?view=netframework-4.8
    64.     public void Load()
    65.     {
    66.         scenesHighScores = null;
    67.  
    68.         // Open the file containing the data that you want to deserialize.
    69.         FileStream fs = new FileStream("DataFile.dat", FileMode.Open);
    70.         try
    71.         {
    72.             BinaryFormatter formatter = new BinaryFormatter();
    73.  
    74.             // Deserialize the hashtable from the file and
    75.             // assign the reference to the local variable.
    76.             scenesHighScores = (List<ScenesHS>)formatter.Deserialize(fs);
    77.         }
    78.         catch (SerializationException e)
    79.         {
    80.             Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
    81.             throw;
    82.         }
    83.         finally
    84.         {
    85.             fs.Close();
    86.         }
    87.  
    88.         // To prove that the table deserialized correctly,
    89.         // display the key/value pairs.
    90.         foreach (var x in scenesHighScores)
    91.         {
    92.             Console.WriteLine($"SceneName: {x.SceneName}, IndexScene: {x.IndexScene}");
    93.             foreach (var h in x.HS)
    94.             {
    95.                 Console.WriteLine($"Name: {h.Name}, Score: {h.Result}");
    96.             }
    97.         }
    98.     }
    99. }
     
  3. jbowers74321

    jbowers74321

    Joined:
    Oct 30, 2019
    Posts:
    25
    i put in what you said and i get this error when i switch public class score: monobehavior to public class HighS
    error CS0246: The type or namespace name 'SerializationException' could not be found (are you missing a using directive or an assembly reference?)

    and if i leave it the way it is i get this error
    error CS0101: The namespace '<global namespace>' already contains a definition for 'Score' because it has the same name as your line 2 in your code.
     
  4. adi7b9

    adi7b9

    Joined:
    Feb 22, 2015
    Posts:
    181
    You need to use [Serialize]
    You have another class with the name Score