IsolatedStorage with XMLSerializer not working together

34 views Asked by At

I've been trying to make a dll for my unity game, by sending an object SaveGame to the plugin, and saving into the IsolatedStorage. But it's not working. This is the code used to save:

 public static void Save(SaveGame filetobeSaved)
    {

        using (IsolatedStorageFile armz = IsolatedStorageFile.GetUserStoreForApplication())
        {
            if (armz.FileExists("save.gd"))
            {
                armz.DeleteFile("save.gd");
            }
            using (IsolatedStorageFileStream file = new IsolatedStorageFileStream("save.gd", System.IO.FileMode.Create, armz))
            {
                XmlSerializer serializer = new XmlSerializer(typeof(SaveGame));
                serializer.Serialize(file, filetobeSaved);
            }} }

When I check this file, using IsoStoreSpy, the file has just this:

 <?xml version="1.0" encoding="utf-8"?>
 <SaveGame xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" />

Why is not saving correctly?

SaveGame.cs

public class SaveGame
{
    public static int gold { get; set; }
         public static int BalasMais { get; set; }

    public static int DanoMais { get; set; }
         public static int SpeedMais { get; set; }
    public static int LifeMais { get; set; }

    public int getGold() { return gold; }
    public int getBalas() { return BalasMais; }
    public int getDano() { return DanoMais; }
    public int getSpeed() { return SpeedMais; }
    public int getLife() { return LifeMais; }
    public SaveGame()
    {
        gold = 0;
        BalasMais = 0;
        DanoMais = 0;
        SpeedMais = 0;
        LifeMais = 0;
    }
    public SaveGame(int g, int b, int d, int s, int l)
    {
        gold = g;
        BalasMais = b;
        DanoMais = d;
        SpeedMais = s;
        LifeMais = l;
    }

}

}

1

There are 1 answers

0
andreycha On

XmlSerializer does not serialize static fields. It can only serialize public instance non-readonly fields and properties. Remove static modifiers and you will get:

<?xml version="1.0" encoding="utf-16"?>
<SaveGame xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <gold>1</gold>
  <BalasMais>2</BalasMais>
  <DanoMais>3</DanoMais>
  <SpeedMais>4</SpeedMais>
  <LifeMais>5</LifeMais>
</SaveGame>

Or, depending on your design, wrap static fields with instance properties (not the methods).