Unity - 反序列化xml文件时出现NullReferenceException

时间:2017-04-17 15:19:02

标签: c# xml unity3d serialization

我序列化一个类Item:

[System.Serializable]
public class Item
{
    public string   name;
    public int      cost;
    public float    weaponRange;
    public Sprite   image;
    public ItemType itemType;

    public enum ItemType   { Item, Armor, Weapon };
    public enum WeaponType { None, ShortSecant, LongSecant, Blunt, Prickly, Bow };
    public enum ArmorType  { None, Cuirass, Helmet, Boots };
    //public enum ItemEffect { None, AddHp };

    public WeaponType   weaponType;
    public int          damages;
    public bool         twoHanded;

    public ArmorType    armorType;
    public int          armorPoints;
    public int          infoIndex = -1; 

    #region [ item property drawer ]

    public bool _expanded     = false;
    public bool _arr_expanded = false;
    public int  _arrLength   = 0;

    #endregion
}

我序列化和反序列化Item的数组,看起来像这样:

public Item [] allItems;

此数组位于EquipmentConatiner类中。 我有一个使用XML操作的所有XML类的抽象类:

using UnityEngine;
using System.IO;

public abstract class XMLBase : MonoBehaviour
{
    public static XMLBase instance { get; private set; }
    protected abstract string Path { get; }

    public FileStream GetStream(bool saveStream)
    {
        return 
            new FileStream(Application.dataPath + Path, saveStream ? FileMode.Create : FileMode.Open);
    }

    protected void Awake()
    {
        instance = this;
    }

    public abstract void SaveData();
    public abstract void LoadData();
}

一个继承自它的类名为ItemsLoader:

using System.Xml.Serialization;
using System.IO;
using System;
using UnityEngine;

public class ItemsLoader : XMLBase
{
    public EquipmentContainer container;

    protected override string Path
    {
        get { return "/StreamingAssets/XML/save.xml"; }
    }

    public override void LoadData()
    {
        FileStream stream = GetStream(false);

        try
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Item[]));
            container.allItems = (Item[])serializer.Deserialize(stream);
        }
        catch(Exception ex)
        {
            Debug.LogError(ex);
        }

        stream.Close();
    }

    public override void SaveData()
    {
        FileStream stream = GetStream(true);

        try
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Item[]));
            serializer.Serialize(stream, container.allItems);
        }
        catch (Exception ex)
        {
            Debug.LogError(ex);
        }

        stream.Close();
    }
}

SaveData方法运行良好,但是当我尝试加载数据时,我有一个NullReferenceException,我不知道为什么......

0 个答案:

没有答案