Hello. Fairly new to unity and was trying to read some data in from a file. I found this Saving and Loading Data: XmlSerializer which i was using to help set up a base data read/write structure. It is currently not throwing any errors, but after I call the load function, I try to query the resulting information to find that it is not being set.
Can anyone tell me what I’m doing wrong?
WeaponContainer.Cs
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using UnityEngine;
[XmlRoot("WeaponCollection")]
public class WeaponContainer {
[XmlArray("Weapons"), XmlArrayItem("Weapon")]
public Weapon[] Weapons;
public void Save(string path)
{
var serializer = new XmlSerializer(typeof(WeaponContainer));
using (var stream = new FileStream(path, FileMode.Create))
{
serializer.Serialize(stream, this);
}
}
public static WeaponContainer Load(string path)
{
var serializer = new XmlSerializer(typeof(WeaponContainer));
using (var stream = new FileStream(path, FileMode.Open))
{
return serializer.Deserialize(stream) as WeaponContainer;
}
}
}
Weapon.Cs
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using UnityEngine;
public class Weapon {
[XmlAttribute("name")]
public string Name;
public float Damage;
public float AttackSpeed;
public float Range;
public bool bIsRanged;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
Load Function in another class
public void fetchWeapons()
{
var weaponCollection = WeaponContainer.Load(Path.Combine(Application.dataPath, "XML/Weapons.xml"));
Debug.Log("Weapons");
Debug.Log(weaponCollection.Weapons[0].Damage);
}
Weapons.xml
<WeaponCollection>
<Weapons>
<Weapon name="a">
<damage>5</damage>
<attackspeed>1</attackspeed>
<range>5</range>
<IsRanged>false</IsRanged>
</Weapon>
<Weapon name="b">
<damage>3</damage>
<attackspeed>0.5</attackspeed>
<range>3</range>
<IsRanged>false</IsRanged>
</Weapon>
</Weapons>
</WeaponCollection>
I am extremly new to both unity and xml read/write so im having a hard time debugging. Any pointers to good resources would also be appreciated.