I'm trying to create a scoring system for a game with multiple levels. For this I'm using the binary formatter instead of playerprefs (I read online that playerprefs are not that secure). I have created the system but whats happening is that the score is not resetting to 0 when I load a new level. If in one level the score was 10 and I start some other level, the score in this level starts from 10 instead of 0. This is the code I have so far:
public class ScoreIncrease : MonoBehaviour
{
public Text scoreTxt;
public int score;
void Start()
{
LoadScore();
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
Save();
}
}
public void Save()
{
score++;
scoreTxt.text = "Score" + score;
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/scoreContainer.dat", FileMode.Create);
ScoreContainer scoreContainer = new ScoreContainer();
scoreContainer.score = score;
bf.Serialize(file, scoreContainer);
file.Close();
}
public void LoadScore()
{
if(File.Exists(Application.persistentDataPath + "/scoreContainer.dat"))
{
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/scoreContainer.dat", FileMode.Open);
ScoreContainer scoreContainer = (ScoreContainer)bf.Deserialize(file);
file.Close();
score = scoreContainer.score;
scoreTxt.text = "Score" + score;
}
}
}
[Serializable]
public class ScoreContainer
{
public int score;
}
How can I change this so that each level has a separate highscore and all levels have a start score of 0?