My save data is being overwritten
Hello, world:
I'm writing a very easy save function in Unity for an iOS game. Though it saves your progress as it goes, however, it deletes the data from all the previously saved levels. Can anyone please help me understand what I am doing wrong? Before I post my code let me provide you with a visual of what is happening right now.
The image above demonstrates what happens after I save my game data and for this part only, it does it right.
But...
When I go to save the data after completing the second level, this suddenly happens:
Level 2 data is saved but the first level data is gone. This is the case for all the other levels.
Here is the code I am using to save the data:
public void Save(int _collectibleCount, int _starCount, int _minutes, int _seconds)
{
SerializableLevelData.LastKeyIndex = 0;
var _level = new LevelContainer();
for (int i = 0; i < PlayerPrefs.GetInt("LevelCounter"); i++)
{
_level.Container.Add(new SerializableLevelData());
if (SceneManager.GetActiveScene().name == _level.Container[i].Key)
{
_level.Container[i].CollectibleCount = (_collectibleCount > _level.Container[i].CollectibleCount) ? _collectibleCount : _level.Container[i].CollectibleCount;
_level.Container[i].GoldStarsCount = (_starCount > _level.Container[i].GoldStarsCount) ? _starCount : _level.Container[i].GoldStarsCount;
_level.Container[i].MinutesCounter = (_level.Container[i].MinutesCounter == 0 || _minutes < _level.Container[i].MinutesCounter) ? _minutes : _level.Container[i].MinutesCounter;
_level.Container[i].SecondsCounter = (_level.Container[i].SecondsCounter == 0 || _seconds < _level.Container[i].SecondsCounter) ? _seconds : _level.Container[i].SecondsCounter;
}
}
PlayerPrefs.SetInt(Constants.LevelFinishedCounter, _levelData.Container.Count -1);
// This is the final resulting JSON from the serialization process
CreateFile(_level);
}
// Finally our save and load methods for the file itself
void CreateFile(LevelContainer _container)
{
PlayerPrefs.SetString("SaveData", JsonUtility.ToJson(_container, true));
Debug.Log("File written.");
}
Some observation though: I am using PlayerPrefs to work around a UnauthorizedAccessException issue I was having before.