• 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 sdgd · Feb 11, 2013 at 06:28 PM · c#saveloadhowtohdd

How To Save Load to Hard Disc Drive C#

using Unity 4.0.1,

Windows 7

C#

I've found this but when I give in first code I start getting errors

 Assets/Scripts/Class/SaveData.cs(13,18): error CS0535: `SaveData' does not implement interface member `System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)'


than if I modify it a bit - following his path don't know why that error go away but still...

 using UnityEngine;
 using System.Collections;
 
 using System.Text;
 //using http://System.IO;
 using System.Runtime.Serialization.Formatters.Binary;
 
 using System;
 using System.Runtime.Serialization;
 using System.Reflection;
 
 
 
 [Serializable ()]
 public class SaveData : ISerializable {
 public bool foundGem1 = false;
 public float score = 42;
 public int levelReached = 3;
 
     public SaveData (SerializationInfo info, StreamingContext ctxt){
         //Get the values from info and assign them to the appropriate properties
         foundGem1 = (bool)info.GetValue("foundGem1", typeof(bool));
         score = (float)info.GetValue("score", typeof(float));
         
         levelReached = (int)info.GetValue("levelReached", typeof(int));
     }
     
     //Serialization function.
     
     public void GetObjectData (SerializationInfo info, StreamingContext ctxt)
     {
     
         info.AddValue("foundGem1", (foundGem1));
         info.AddValue("score", score);
         info.AddValue("levelReached", levelReached);
     }
     public void Save () {
 
         SaveData data = new SaveData ();
     
         Stream stream = File.Open("MySavedGame.game", FileMode.Create);
         BinaryFormatter bformatter = new BinaryFormatter();
         bformatter.Binder = new VersionDeserializationBinder();
         Debug.Log ("Writing Information");
         bformatter.Serialize(stream, data);
         stream.Close();
     }
 
     public void Load () {
 
         SaveData data = new SaveData ();
         Stream stream = File.Open("MySavedGame.gamed", FileMode.Open);
         BinaryFormatter bformatter = new BinaryFormatter();
         bformatter.Binder = new VersionDeserializationBinder();
         Debug.Log ("Reading Data");
         data = (SaveData)bformatter.Deserialize(stream);
         stream.Close();
     }
     
 public sealed class VersionDeserializationBinder : SerializationBinder{
         public override Type BindToType( string assemblyName, string typeName ){
             if ( !string.IsNullOrEmpty( assemblyName ) && !string.IsNullOrEmpty( typeName ) ){
                 Type typeToDeserialize = null;
                 
                 assemblyName = Assembly.GetExecutingAssembly().FullName;
                 // The following line of code returns the type.
                 typeToDeserialize = Type.GetType( String.Format( "{0}, {1}", typeName, assemblyName ) );
                 return typeToDeserialize;
             }
             return null;
         }
     }
 }
 
 


and now I'm getting errors:

 Assets/Scripts/Class/SaveData.cs(41,17): error CS0246: The type or namespace name `Stream' could not be found. Are you missing a using directive or an assembly reference?


and for the last class inside class I thought it would be wrong but it seems it's not as I get no errors so I'm even more confused as it seems I did steps correctly

I basically puted all in on bottom of each

I really don't understand 5% of this code

is it really necessary to write 3 pages just to save 1 int on HDD if not can someone show me simpler code how to save data on HDD so I could read write on it

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

2 Replies

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

Answer by Bunny83 · Feb 11, 2013 at 10:21 PM

Serialization is ment to provide a more or less type safe way to save arbitrary classes to a file and read them back in. If you have complex classes it can get very messy if you save things "manually" to a file. If the data you want to save isn't that complex you can simply use a BinaryWriter / Reader:

     // C#
     int someValue = 4;
     
     void SaveData()
     {
         using(var writer = new BinaryWriter(File.OpenWrite("FileName")))
         {
             writer.Write(someValue);
             writer.Close();
         }
     }
     
     void LoadData()
     {
         using(var reader = new BinaryReader(File.OpenRead("FileName")))
         {
             someValue = reader.ReadInt32();
             reader.Close();
         }
     }

You need of course the namespace System.IO which contains any classes involved with file IO (input / output).

Just a little warning:
If you use this method to save binary data to a file it looses it's type. The binary data is just a stream of bytes. That's why it's important to read the exact same data that you have written. The Write method accepts a lot different types and it depends on the type you pass to the function what is actually written to the file.

The "normal" int-type is actually an int32. That means one int needs 32 bits (or 4 bytes) of memory. When you read the data back in you have to use the correct function which returns the exact type you've written.

Comment
Add comment · Show 1 · 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
avatar image sdgd · Feb 12, 2013 at 05:10 PM 0
Share

thanks it works

avatar image
2

Answer by Dave-Carlile · Feb 11, 2013 at 09:16 PM

If you just have a small amount of data to save, I would recomment using the built-in PlayerPrefs class.

Comment
Add comment · Show 1 · 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
avatar image sdgd · Feb 11, 2013 at 09:32 PM 0
Share

and If I have large like lots of game objects

but I'd like to learn just 1 int just to get started?

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.

Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.



Follow this Question

Answers Answers and Comments

11 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

C# line into Javascript help 1 Answer

calling c# method from different c# file 1 Answer

Hack and Slash tutorial Stack Overflow problem 1 Answer

Is it safe to store & read data to XML file for mobile game development 1 Answer

how to find no file exists? 2 Answers


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