开发者

Saving Level in XML

开发者 https://www.devze.com 2023-02-27 22:17 出处:网络
Greetings to everyone. I am creating a Level with objects (Tiles, Obstacles, Character). I am experiencing a problem. The serialization is successfully made, but I get empty Lists. I want to serialize

Greetings to everyone. I am creating a Level with objects (Tiles, Obstacles, Character). I am experiencing a problem. The serialization is successfully made, but I get empty Lists. I want to serialize and save the attributes of each object. For example:

public class Obstacle 
{
    public Texture2D ob_tex;
    public Rectangle ob_rec;
   开发者_StackOverflow中文版 public bool ob_clic;


    Obstacle() { } // Create Constructor
}

I use this code to save the level:

public class Level 
{

    public List<Obstacle> obstacles;
    public LevelFile levelfile;

    public Level()
    {
        obstacles = new List<Obstacle>();
    }

    public class LevelFile
    {
        public List<Obstacle> obstacles;
    }

    public void Save(String path/*, LevelFile levelfile*/)
    {
        levelfile = new LevelFile();
        levelfile.obstacles = obstacles;
        XmlSerializer serializer = new XmlSerializer(typeof(LevelFile));
        using (StreamWriter streamWriter = new StreamWriter(path))
        {
            serializer.Serialize(streamWriter, levelfile);
        }   
    }

}

But I get an xml file which is like this:

<LevelFile<obstacles /></LevelFile>

And nothing in it(Rectangle value, Texture and bool)....


Well, according to your code you're saving a new LevelFile() which has an obstacles member that's a list, which you set from the obstacles member in your Level() constructor, which is an empty list. Thus the XML is right, you are outputting a file with an empty list which shows as the empty tag.

So it looks like your code is correct. If you add an obstacle to your list in the constructor or save, you'll see that it's actually working correctly:

public Level()
{
    obstacles = new List<Obstacle>
        {
            new Obstacle { /* set your properties here */ }
        };
}
0

精彩评论

暂无评论...
验证码 换一张
取 消