Loading and Saving a Serializable Array.
I'm not receiving any errors in Unity, but Data is not saving or loading. using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using UnityEngine.UI; using System.Runtime.Serialization.Formatters.Binary; using System.IO;
public class SavedScore : MonoBehaviour { public static SavedScore score;
public int[] lvlScore;
public void Save(int score)
{
lvlScore[GameControl.control.currentLevel] = score;
BinaryFormatter binaryFormatter = new BinaryFormatter();
FileStream file = File.Create(Application.persistentDataPath + "/FWScore.dat");
FWScore data = new FWScore();
for (int i = 0; i == 199; i++){
data.lvlScore[i] = lvlScore[i];
}
binaryFormatter.Serialize(file, data);
file.Close();
}
public void Load()
{
if (File.Exists(Application.persistentDataPath + "/FWScore.dat"))
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
FileStream file = File.Open(Application.persistentDataPath + "/FWScore.dat", FileMode.Open);
FWScore data = (FWScore)binaryFormatter.Deserialize(file);
file.Close();
for (int i = 0; i == 199; i++)
{
lvlScore[i] = data.lvlScore[i];
}
}
}
}
@clintbaucom - Have you already solved this? If not, you seem to have couple of problems....
Answer by eses · Aug 26, 2018 at 11:20 AM
Hi @clintbaucom
Your script has some issues that would have been solved by reading and debugging the code by printing out the contents of your saved data / array.
You don't show serializable FWScore class, but I expect it just mirrors lvlScore array:
[System.Serializable]
public class FWScore
{
public int[] lvlScore;
}
First you have this:
FWScore data = new FWScore();
for (int i = 0; i == 199; i++){
data.lvlScore[i] = lvlScore[i];
}
Your FWScore contains most like an array, so you should initialize it's size. Also your loop condition is bit strange. What if you don't have exactly this amount of values in use? Maybe make it match lvlScore length?
FWScore data = new FWScore();
data.lvlScore = new int[lvlScore.Length];
for (int i = 0; i < lvlScore.Length; i++)
{
data.lvlScore[i] = lvlScore[i];
}
Then the Load() method. Here you could just first do:
if (File.Exists(Application.dataPath + "/FWScore.dat") == false)
return;
Here too, you should initialize lvlScore array in this class, when loading the data in:
lvlScore = new int[data.lvlScore.Length];
for (int i = 0; i < data.lvlScore.Length; i++)
{
lvlScore[i] = data.lvlScore[i];
}