XNA使用content.load XML总是返回相同的对象?

时间:2012-03-12 20:20:22

标签: xml xna-4.0 xml-deserialization content-pipeline

我正在尝试将spmlesheet数据用于xml文件;我有一个框架类,可以保存一个矩形或另一个框架列表(它可以是一个框架本身,或更多框架的持有者)。 xml保存帧的所有矩形。 我已将xml添加到内容项目中,并使用Content.load(“xmlname”)加载它。

使用一次时,这一切都完美无缺。但是当我创建两个共享相同spritesheet的对象(因此相同的xml数据文件)时,当这两个对象在同一帧上时,它们会消失。经过很多挫折后,我发现xml文件总是返回相同的对象,因此共享帧,因此它一次只能绘制一个帧。

这是xml文件的一小部分:

<?xml version="1.0" encoding="utf-8"?>

  

<rect>0 0 0 0</rect>

<frames>

  <Item>
    <rect>0 0 0 0</rect>
    <frames>

      <Item>
        <rect>19 27 15 22</rect>
        <frames></frames>
        <label>DOWN</label>
      </Item>

      <Item>
        <rect>2 27 15 23</rect>
        <frames></frames>
        <label>DOWN</label>
      </Item>

      <Item>
        <rect>19 27 15 22</rect>
        <frames></frames>
        <label>DOWN</label>
      </Item>

      <Item>
        <rect>36 27 15 23</rect>
        <frames></frames>
        <label>DOWN</label>
      </Item>

    </frames>
    <label>DOWN</label>
  </Item>

剥离了该类的版本:

    public class Frame
{
    public Rectangle rect; //means this is an image

    private Renderable renderable = null;

    private List<Frame> frames;

    private Texture2D texture;
    private int currentFrame = 0;

示例用法:

    Sprite sprite1 = new Sprite();
    sprite1.frame = Content.load<Frame>("xml");
    sprite1.frame.getFrame(0).alpha = 0.5f; 

    Sprite sprite1 = new Sprite();
    sprite2.frame = Content.load<Frame>("xml"); //<--- doesn't return a new object, returns the same object as sprite 1 uses
     //frame  0 in sprite 2 has an alpha of 0.5 aswell, without having modified it

我尝试手动反序列化xml,但反序列化列表是一场噩梦。 我在这里做错了吗?看起来很奇怪,它返回相同的对象

1 个答案:

答案 0 :(得分:2)

这是设计的。在大多数情况下,您只想加载一次资产,然后重复使用它。多次加载会浪费时间和记忆。

理想情况下,从磁盘加载的任何资产都应该是不可变对象,因此您应该更改设计,这样就不需要修改它们的字段。

但有时那是不可能的。下一个最佳解决方案是在要创建多个副本的类上实现ICloneable

难以实现正确且有点丑陋的替代方法是继承ContentManager并覆盖其方法,以便每次加载资产,如this blog post中所述。

相关问题