0

I serialize a class 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
}

I serialize and deserialize an array of Item, that looks like that:

public Item[] allItems;

This array is in class EquipmentConatiner. And I have an abstract class for all XML classes that uses XML operations:

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();
}

And a class that inherits from it named 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();
    }
}

The SaveData method works well, but when I try to load data, I have a NullReferenceException, and I don't know why..

TKK
  • 178
  • 1
  • 7

0 Answers0