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 /
avatar image
0
Question by alexhapki · Sep 01, 2015 at 09:40 AM · listsave dataserialize

Serialize a list to save it

Hi everyone, I am trying serializing a list, essentially with a Name (Player Attribute) and its value (created randomly). I managed to get Attribute Name and its value into a List, and it seems to be working well. It prints out Attribute Name and value. Now, how I can serialize the list to save those values? I tried different ways without success, I cant think on what I need to add to finish this test. The purpose is to be able to save player data and recover it later. I managed to do it easily using a list of "int" variables, serializing them and get them saved in a long list, do it one by one and then save all data together (Int strength, int agility, etc) but it is tedious as for my project there is a good number of attributes, skills, etc. and when recovering the data, I also need a long list of "int" variables to recover data. I used only 3 Attributes just for this example.

I pasted my code below. Could anyone please help me? Thank you in advance.

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 using System.Runtime.Serialization.Formatters.Binary;
 using System.IO;
 
 
 [System.Serializable]
 
 public class TestSaving : MonoBehaviour 
 {
 
 
     public int minValue = 6;
     public int maxValue = 19;
     int diceRoll;
     string name;
     int value;
 
     // Use this for initialization
     void Start () 
     {
 
         BinaryFormatter bf = new BinaryFormatter();
         FileStream file = File.Create(Application.persistentDataPath + "/testSaving.dat");
 
 
         List <TestSaving> attributes = new List<TestSaving>();
 
 
         for (int cnt = 0; cnt < System.Enum.GetValues(typeof(AttributeName)).Length ; cnt ++)
         {
             Debug.Log ((AttributeName)cnt);
             string newName = ((AttributeName)cnt).ToString();
             DiceRolling (minValue, maxValue);
             Debug.Log (diceRoll);
             attributes.Add (new TestSaving (newName, diceRoll));
 
 
         }
 
         foreach (TestSaving attr in attributes)
         {
 
             print (attr.name + "/" + attr.value);
             // what to add here so both attr.name and attr.value are serialized and can be saved?
         }
 
         bf.Serialize (file, xxxx );   // here what do we add? 
         
         file.Close ();
     }
 
 
     public TestSaving (string newName, int newValue)
     {
         name = newName;
         value = newValue;
     }
 
 
     public enum AttributeName
     {
         Strength,
         Agility,
         Constitution
     }
 
     public void DiceRolling (int minValue, int maxValue)
     {
         diceRoll = Random.Range (minValue, maxValue);
         //    Debug.Log ("Min_; " + minValue + " /Max_; " + maxValue + " /DiceRoll :" + diceRoll);
     }
 
 }






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

3 Replies

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

Answer by alexhapki · Sep 02, 2015 at 06:48 AM

Hi Landern, Thanks for that. it didn't work for me. Adding "attributes" as you mentioned returns an error;

SerializationException: Type UnityEngine.MonoBehaviour in assembly UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null is not marked as serializable. System.Runtime.Serialization.FormatterServices.GetSerializableMembers (System.Type type, StreamingContext

The link you provided didn't work for my case, however it was interesting to learn more on the matter. Thanks for that!.

I tried loading later the data and it looks like there is not data. After dedicating few hours to it I tried another approach, Hastable. It looks like it might work well for my case. I found very useful the following; https://msdn.microsoft.com/en-us/library/c5sbs8z9(v=vs.110).aspx

I changed a bit the code to test it on Unity, and worked well. I write the code for Attributes and their values in the coming days and let you know how it goes, in case any other people is looking for similar solutions. First quick test on Unity went well, I played the script on an empty gameobject, saved data, then stop the game, played it again, and loaded the data well.

Looking good !!!

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 alexhapki · Sep 03, 2015 at 09:58 AM 0
Share

Hi again, This is how my little test worked out; I deserialized the data and it worked well.

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

public class App : $$anonymous$$onoBehaviour { public int $$anonymous$$Value = 6; public int maxValue = 19; public int diceRoll; public string name; public int value;

 void Start ()
 {
     $$anonymous$$Value = 6;
     maxValue = 19;
 }

 void Update ()
 {
 //    Debug.Log (UnityEngine.Random.Range ($$anonymous$$Value, maxValue));

     if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.S))
     {
         Serialize();

     }

     if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.L))
     {
         Deserialize();
         
     }
 }

 public App ( string newName, int newValue)
 {
     name = newName;
     value = newValue;
 }
 
 
 public enum AttributeName
 {
     Strength,
     Agility,
     Constitution
 }


 void Serialize() 
 {
     // Create a hashtable of values that will eventually be serialized.
     Hashtable addresses = new Hashtable();

     /*
     addresses.Add("Eddie", "123 $$anonymous$$ain Street, Redmond, WA 98052");
     addresses.Add("Freddy", "987 Pine Road, Phila., PA 19116");
     addresses.Add("$$anonymous$$ary", "PO Box 112233, Palo Alto, CA 94301");
     */

     for (int cnt = 0; cnt < System.Enum.GetValues(typeof(AttributeName)).Length ; cnt ++)
     {
         Debug.Log ((AttributeName)cnt);
         string newName = ((AttributeName)cnt).ToString();
         diceRoll = UnityEngine.Random.Range ($$anonymous$$Value, maxValue); 

         Debug.Log (diceRoll);
         addresses.Add (newName, diceRoll);            
     }
     // To serialize the hashtable and its key/value pairs,   
     // you must first open a stream for writing.  
     // In this case, use a file stream.
     FileStream fs = new FileStream("DataFile.dat", File$$anonymous$$ode.Create);
     
     // Construct a BinaryFormatter and use it to serialize the data to the stream.
     BinaryFormatter formatter = new BinaryFormatter();
     try 
     {
         formatter.Serialize(fs, addresses);
     }
     catch (SerializationException e) 
     {
         Console.WriteLine("Failed to serialize. Reason: " + e.$$anonymous$$essage);
         throw;
     }
     finally 
     {
         fs.Close();
         Debug.Log ("Done Ser");
     }

     foreach (DictionaryEntry de in addresses) 
     {
     
         print (de.$$anonymous$$ey + "/" + de.Value);
     }
 }
 
 
 static void Deserialize() 
 {


     // Declare the hashtable reference.
     Hashtable addresses  = null;
     
     // Open the file containing the data that you want to deserialize.
     FileStream fs = new FileStream("DataFile.dat", File$$anonymous$$ode.Open);
     try 
     {
         BinaryFormatter formatter = new BinaryFormatter();
         
         // Deserialize the hashtable from the file and  
         // assign the reference to the local variable.
         addresses = (Hashtable) formatter.Deserialize(fs);
     }
     catch (SerializationException e) 
     {
         Console.WriteLine("Failed to deserialize. Reason: " + e.$$anonymous$$essage);
         throw;
     }
     finally 
     {
         fs.Close();


     }
     

     {
         Console.WriteLine("{0} lives at {1}.", de.$$anonymous$$ey, de.Value);
         print (de.$$anonymous$$ey + "/" + de.Value);
     }
 }

}

avatar image
1

Answer by Landern · Sep 01, 2015 at 02:13 PM

Providing that your class TestSaving is set for serialization(and any fields set to NonSerialized where needed), you can pass in the reference to the list object. In your case:

 bf.Serialize (file, attributes);

an easy to follow example: http://www.dotnetperls.com/serialize-list

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

Answer by gamesappstudio · Jul 11, 2017 at 06:57 PM

You can find plugin here (easy to implement ) http://assetstore.unity3d.com/en/#!/content/94493

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

29 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

Related Questions

[SOLVED] "IOException: Sharing violation on path" Trying to save multiple files 4 Answers

Help! my list won't remove its elements... 0 Answers

Delete corrupt file rather than throw an exception 0 Answers

Question about Unity serialize system 1 Answer

How can I save this objects ? 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