- Home /
InvalidCastException: Cannot cast from source type to destination type.
Hello all, I have been reading to find the answer for this error for hours now, and no luck.
I am getting this error when trying to cast binary stream to array. I would normally look for solutions directly in code but the catch is this same script works in other scene just fine. Am I wrong to use same script or something?
BinaryFormatter bf = new BinaryFormatter();
FileStream file = File.Open(path, FileMode.Open);
SaveData data = (SaveData)bf.Deserialize(file);
file.Close();
levelSaveArray = data.Tiles;
Answer by HarshadK · Dec 09, 2016 at 05:48 AM
What this means it the file at path
does not actually store type SaveData
. Is the file you are trying to access in both the scenes (working scene and not working one) same? If not you should check for the file you are trying to access here.
Files are the same. Path is the same. Scripts are identical, except for the name of script and the name of class. There is serialized simple array in that file and it worked as it should in previous scene. I checked everything around this(all other and everything looks fine. Is there a way to see what type of data is in file stream before casting?
Answer by denmla1000 · Dec 09, 2016 at 10:04 PM
I found it.
The same script is the error :)
When I create those files that I use for loading later :) I am using class SaveData. Later, in other scene, I used the same script with "in line" class SaveData and I change it to SaveData2 so it can compile. When it tries to cast, it is trying to cast SaveData to SaveData2 it produces the error. I forgot that class as a type of data is different then when saved.
Your answer
Follow this Question
Related Questions
Serialization depth limit exceeded 3 Answers
Why is my file path invalid? 2 Answers
Editor Window Serialization not Working as Expected 2 Answers
Casting error on multiple emitters 3 Answers
Unity Serializer scripting error 1 Answer