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