I encountered this error when trying to load an XML file through three scripts: one called Item, another ItemCollection, and the script to load the XML file.
Item:
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
using UnityEngine;
public class Item : MonoBehaviour {
[XmlAttribute("id")]
public string id;
[XmlAttribute("Nome")]
public string Nome;
[XmlAttribute("Preco")]
public float Preco;
}
ItemCollection
using System.Collections;
using System.Collections.Generic;
using System.Xml.Serialization;
using UnityEngine;
using System.IO;
[XmlRoot("DataBase")]
public class ItemCollection : MonoBehaviour {
[XmlArray("Produtos")]
[XmlArrayItem("Produto")]
public List<Item> Produtos = new List<Item>();
public static ItemCollection Load(string path)
{
TextAsset _xml_ = Resources.Load <TextAsset>(path);
XmlSerializer serializer = new XmlSerializer(typeof(ItemCollection));
StringReader reader = new StringReader(_xml_.text);
ItemCollection Produtos = serializer.Deserialize(reader) as ItemCollection;
reader.Close();
return Produtos;
}
}
Loader:
using System.Collections;
using System.Collections.Generic;
using System.Xml.Linq;
using UnityEngine;
public class LoadXml : MonoBehaviour {
public const string path = "Nomes_E_Precos";
void Start () {
ItemCollection itemCollection = ItemCollection.Load(path);
foreach (Item Produto in itemCollection.Produtos)
{
Debug.Log(Produto.Nome + Produto.id + Produto.Preco);
}
}
}
However, give me the error (in the engine) in the title:
To be XML serializable, types which inherit from IEnumerable must have an implementation of Add (System.Object)
Any solution?