Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by BugFighter · Nov 01, 2015 at 11:00 PM · c#deserializationinvalidcastexception

Deserializing problem at runtime, InvalidCastException

I was just messing around with serialization, when a strange error was popping up, only at runtime though. It says:

InvalidCastException: Cannot cast from source type to destination type. MyScript.Load ()

The adressed C# script (MyScript) contains this code:

     public static int highscore = 0;        //saved Highscore
     public static int collectedPoints = 0;    //Points collected on this account
     public static int lifetimeScore = 0;    //count of all points ever collected
 
     public static void Load()
     {
         if(File.Exists(Application.persistentDataPath + "/saveFiles.xyz"))
         {
             BinaryFormatter bf = new BinaryFormatter();
             FileStream file = File.Open(Application.persistentDataPath + "/saveFiles.xyz", FileMode.Open);
             SaveValues.highscore = (int)bf.Deserialize(file);
             SaveValues.collectedPoints = (int)bf.Deserialize(file);
             SaveValues.lifetimeScore = (int)bf.Deserialize(file);
             file.Close();
         }
     }
 
     public static void Save()
     {
         BinaryFormatter bf = new BinaryFormatter();
         FileStream file = File.Create (Application.persistentDataPath + "/saveFiles.xyz");
         bf.Serialize(file, SaveValues.highscore);
         bf.Serialize(file, SaveValues.collectedPoints);
         bf.Serialize (file, SaveValues.lifetimeScore);
         file.Close();
     }
 
     public static void Reset()
     {
         if (File.Exists (Application.persistentDataPath + "/saveFile.xyz"))
         {
             File.Delete (Application.persistentDataPath + "/saveFile.xyz");
             Application.LoadLevel(0);
         }
     }

SavedValues is the class containing these variables. I think the error is pointing towards the "SavedValues.lifetimeScore"-line in the Load()-function. What am i missing?

Thanks in advance.

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
2
Best Answer

Answer by Bunny83 · Nov 02, 2015 at 03:10 AM

Deserialize will deserialize an object graph from the given stream. It isn't ment to be used several times in a row. You should serialize one thing and that's what you will get back when you deserialize the stream. Usually you would use a data class like this one:

 [System.Serializable]
 public class SaveData
 {
     public int highscore = 0;
     public int collectedPoints = 0;
     public int lifetimeScore = 0;
 }

You can either create a temporary instance of that class, assign your values to the fields and then serialize it, or directly replace your static variables with a single variables to an instance of that SaveData class.

 public static SaveData data = new SaveData();


That way you always store the data directly into the instance. To access a value you would need to use

 MyScript.data.highscore = 42;
 // instead of
 MyScript.highscore = 42;

Now you can simply serialize and deserialize your SaveData class. When you deserialize it you will simple replace the current instance with the deserialized version:

 data = (SaveData)bf.Deserialize(file);


Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

Making a bubble level (not a game but work tool) 1 Answer

An OS design issue: File types associated with their appropriate programs 1 Answer

System.Xml.XmlException: Root element is missing 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges