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 /
  • Help Room /
This question was closed Apr 26, 2018 at 07:40 AM by tormentoarmagedoom for the following reason:

The question is answered, right answer was accepted

avatar image
0
Question by Math0424 · Apr 24, 2018 at 12:40 AM · databaseloadingsavingdatastorage

Saving data with files

So i followed the tutorials on how to use FileStream and binary formatter and came up with the code below, my issue is saving and loading from another C# script...

what I want it to do:

  1. all setting are stored under a C# script called. GameData (all are public static ints)

  2. the SaveLoad script will take the GameData script and store everything in a binary file

  3. then when the program starts it will call the GameData binary file and write i into the GameData C# script
    .

    using System.Collections; using System; using System.Collections.Generic; using UnityEngine; using System.Runtime.Serialization.Formatters.Binary; using System.IO;

    public class SaveLoad : MonoBehaviour {

      public static void Save()
         {
             BinaryFormatter bf = new BinaryFormatter();
             FileStream stream = new FileStream(Application.persistentDataPath + "/GameData.dat", FileMode.Create);
     
             GameData data = new GameData();
     
             bf.Serialize(stream, data);
             stream.Close();
         }
     
         public void Awake()
         {
             if(File.Exists(Application.persistentDataPath + "/GameData.dat"))
             {
                 BinaryFormatter bf = new BinaryFormatter();
                 FileStream stream = new FileStream(Application.persistentDataPath + "/GameData.dat", FileMode.Open);
     
                 GameData data = bf.Deserialize(stream) as GameData;
     
                 stream.Close();
             }
             else
             {
                 Debug.Log("GameData.dat not found!");
             }
         }
     
     
     }
    
    

and the GameData Look like this:

.

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 [System.Serializable]
 public class GameData {
 
     public int musicVolume;
     public int gameVolume;
     public int firstPlay;
     public int mapSize;
     public int coins;
 
 }
 

I've tried everything i can think of and look around but couldn't find anything how can i do this or is it possible?

Comment
Add comment · Show 3
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 Math0424 · Apr 24, 2018 at 12:26 PM 0
Share

any Ideas?

avatar image Hellium Math0424 · Apr 24, 2018 at 12:32 PM 0
Share

AFAI$$anonymous$$, static fields can't be serialized. Remove the static keyword and try again.

avatar image Math0424 Hellium · Apr 24, 2018 at 09:06 PM 0
Share

That didnt work, is something wrong with my code?

1 Reply

  • Sort: 
avatar image
1
Best Answer

Answer by Bunny83 · Apr 25, 2018 at 03:33 AM

There is several wrong / strange with your code. First of all you initially had your variables static. Though as Hellium said static variables are not serialized as they do not belong to an instance of the class.


Inside your Save method you create a new instance of your "GameData" class which you serialize and write to disk. However you never set any of the fields of that class. When you create a new instance of the class all variables will get their default values of "0".

  GameData data = new GameData(); // new instance of "GameData"
  bf.Serialize(stream, data);  // serializing that new instance to disk.



Likewise when you're deserializing your data you correctly recreate the class instance from the serialized information and store it in the local "data" variable. However you don't do anything with that data after deserialization. The local variable is only valid inside your Awake method.


Since you initially had the variables static you probably accessed them from several other scripts directly. Of course this doesn't work when you have an instance of a class. The easiest solution is to use a simple singleton. Change your GameData class to:

 [System.Serializable]
 public class GameData
 {
     public static GameData Instance = new GameData();
     
     public int musicVolume;
     public int gameVolume;
     public int firstPlay;
     public int mapSize;
     public int coins;
 }


That way you actually have a single instance of your class stored in a static variable. Now instead of doing GameData.musicVolume you would do GameData.Instance.musicVolume.


Now when serializing the data you don't want to create a new empty class since it won't contain any data. Instead just serialize our singleton instance:

 bf.Serialize(stream, GameData.Instance); 


And when deserializing you just replace the old singleton with the new one:

 GameData.Instance = (GameData)bf.Deserialize(stream);


Also generally avoid using an "as" cast if you do not perform a null check afterwards. An as cast can hide / delay problems and just makes it harder to debug. A normal cast will throw an exception if the cast fails and gives you a proper error message what went wrong.

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 Math0424 · Apr 25, 2018 at 09:04 PM 0
Share

thank you for your help here's a reward (my only reward point)

Follow this Question

Answers Answers and Comments

141 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 avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Spawning loot only the first time a level is loaded 1 Answer

Why is the BinaryFormatter's output human-readable? 0 Answers

Saving and loading an int variable on Android 1 Answer

Do we have to open SavedGame every time we do a CommitUpdate when using cloud PlayGames services? 1 Answer

Spliting text and WWWform "if" problem 0 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