S
S
Sergey Izmodenov2021-01-31 20:47:29
Unity
Sergey Izmodenov, 2021-01-31 20:47:29

Error with deserialization of the save file. What is the problem?

There are two scripts, one of them is just a trigger at the entrance to which, a unit must be added to the variable that is in the save file, and in the second script, the save file must be deserialized, and this unit must go further through the program. But in the second script, unity swears at this line: "SaveData data = (SaveData)bf.Deserialize(file);" with the error: "InvalidCastException: Specified cast is not valid." Any solutions?
Trigger code:

public void UnlockLevel()
    {

            BinaryFormatter bf = new BinaryFormatter();
            FileStream file = File.Create(Application.persistentDataPath
              + "/MySaveData.dat");
            SaveData data = new SaveData();
            data.savedLevels++;
            bf.Serialize(file, data);
            file.Close();
            Debug.Log("Game data saved!");
            Invoke("LoadMainMenu", 1f);
        
    }


Script code with disserialization:

if (File.Exists(Application.persistentDataPath
             + "/MySaveData.dat"))
            {
                BinaryFormatter bf = new BinaryFormatter();
                FileStream file =
                  File.Open(Application.persistentDataPath
                  + "/MySaveData.dat", FileMode.Open);
                SaveData data = (SaveData)bf.Deserialize(file);
                file.Close();
                LevelComplete = data.savedLevels;
                Debug.Log("Game data loaded!");
            }

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question