Saving serialization data with File.CreateNew and xml help.

Hi,

I’m trying to save game data using xml serialization. I think I coded it correctly but I’m not sure So far nothing is saved. I think I created the proper container files.

Vivienne

// Initialize
    void Initialize ()
    {
        bool loadingFailed;

        // Load Resources
        string path = Application.persistentDataPath + "/SaveGamesData/SaveGame.xml";

        // loading failed
        if (File.Exists (path) == false) {
            // Create a new container
            SaveGameContainer newSaveGames = new SaveGameContainer ();

            newSaveGames.SaveGamesData = new List<SaveGameData> ();
      
            SaveGameData test = new SaveGameData ();

            newSaveGames.SaveGamesData.Add (test);
            newSaveGames.SaveGamesData.Add (test);
            newSaveGames.SaveGamesData.Add (test);
            newSaveGames.SaveGamesData.Add (test);
            newSaveGames.SaveGamesData.Add (test);
            newSaveGames.SaveGamesData.Add (test);
            newSaveGames.SaveGamesData.Add (test);
            newSaveGames.SaveGamesData.Add (test);

            // create serializer
            var serializer = new XmlSerializer (typeof(SaveGameContainer));

            // create filestream
            var stream = File.Open (path, FileMode.CreateNew);
  
            // write to stream
            serializer.Serialize (stream, newSaveGames);

            // Close
            stream.Close ();
        }
    }

Additional files

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Xml;
using System.Xml.Serialization;
using System;

[Serializable]

public class SaveGameData
{
    [XmlAttribute ("Level")]
    public int Level = 0;

    [XmlElement ("Score")]
    public int Score = 0;
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Xml;
using System.Xml.Serialization;
using System;

[XmlRoot ("SaveGameContainer")]

public class SaveGameContainer
{
    [XmlArray ("SaveGames")]
    [XmlArrayItem ("SaveGameData")]
    public List<SaveGameData> SaveGamesData = new List<SaveGameData> (8);
}

Consider using JsonUtility.

1 Like

Was just going to post the same thing. And if not that, Json.net. Json is more human readable (and editable) and likely faster than .Net XML. But most importantly it takes far fewer lines of code.

To the problem at hand, did you debug where execution goes wrong?

1 Like

PS common issues with accessing files are exceptions, ie if the path does not exist or you don‘t have write permission.

Thanks all. It’s working now.