'When loading data it gives an error " InvalidCastException: Specified cast is not valid "

e.g. I want to select a character and save his number

private Storage storage;
void Awake()
{
   storage = new Storage();
}
public void SelectChar1()
    {
     numberChar = 1;//byte
     storage.Save(DataPlayerSave);//save works fine
    }

on awakening, the number is loaded

private DataPlayerSave dataPlayer;
private byte numberChar;

private void Awake()
      {
        dataPlayer = (DataPlayerSave)storage.Load(new DataPlayerSave());
        numberChar = dataPlayer.numerChar;
      }

I tried to divide the data into several parts and one large file, the result is almost always the same (sometimes everything works)

public class Storage()
{
    public object Load(object saveDataByDefault)
        {
            filePath = Application.persistentDataPath + "/saves/GameSave.save";
            if (!File.Exists(filePath))
            {
                if (saveDataByDefault != null)
                {
                    Save(saveDataByDefault);
                    return saveDataByDefault;
                }
            }
            var file = File.Open(filePath, FileMode.Open);
    
            var saveData = formatter.Deserialize(file);
            file.Close();
            return saveData;
        }
}

There are also similar classes that load data at the beginning of the scene. If there are 2 or more of them, then it gives an error, if 1, then everything works. I tried to set the sequence using the Coroutine did not help. When loading data it gives an error "InvalidCastException: Specified cast is not valid."

dataPlayer = (DataPlayerSave)storage.Load(new DataPlayerSave());



Solution 1:[1]

if formatter is BinaryFormatter: please don't do that - it will hurt you; as for the exception: fundamentally, use a debugger and step through the code. In particular, if you say that the exception is coming from:

dataPlayer = (DataPlayerSave)storage.Load(new DataPlayerSave());

then we can assume that Load is not returning a DataPlayerSave. So: what is it? We can't tell you, but: you can find out:

var obj = storage.Load(new DataPlayerSave());
var type = obj.GetType(); // put a break-point here
Log(type.FullName); // or just log it
dataPlayer = (DataPlayerSave)obj;

and investigate what exactly obj is. Note that BinaryFormatter is very brittle as you change types (rename, move, refactor, etc) - but that isn't even the top reason not to use it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Marc Gravell