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);
}
}
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 !!!
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);
}
}
}
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
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