我正在尝试实现保存和加载机械师到我的游戏。然而,由于某种原因,它不想工作。我一直得到相同的错误消息:XmlException:根级别的数据无效。行1,位置1.
。下面是创建序列化xml文件的代码:
public void Save()
{
Save newsave = new Save();
if (Time.timeScale == 0)
{
int unit_id = 0;
GameObject[] units = new GameObject[check_number_of_units()];
GameObject[] friendlies = GameObject.FindGameObjectsWithTag("Friend");
GameObject[] enemyosldiers = GameObject.FindGameObjectsWithTag("Enemy");
GameObject[] allunits = enemyosldiers.Concat(friendlies).ToArray();
foreach (GameObject g in allunits)
{
Debug.Log(unit_id);
Debug.Log(check_number_of_units());
units[unit_id] = g;
unit_id++;
}
newsave.cash = id.cash;
newsave.enemy_cash = id.enemycash;
newsave.units = units;
newsave.scenename = SceneManager.GetActiveScene().name;
FileStream file = File.Create(Application.persistentDataPath + "/gamesave.save");
DataContractSerializer bf = new DataContractSerializer(newsave.GetType());
MemoryStream streamer = new MemoryStream();
bf.WriteObject(streamer, newsave);
file.Write(streamer.GetBuffer(), 0, streamer.GetBuffer().Length);
file.Close();
}
}
以下是保存类:
[System.Serializable]
[DataContract]
public class Save
{
[DataMember]
public int cash;
[DataMember]
public int enemy_cash;
[DataMember]
public string scenename;
[DataMember]
public GameObject[] units;
}
下面是反序列化代码:
public void Load()
{
if (File.Exists(Application.persistentDataPath + "/gamesave.save"))
{
Save loadedsave = new Save();
DataContractSerializer bf = new DataContractSerializer(loadedsave.GetType());
FileStream file = File.Open(Application.persistentDataPath + "/gamesave.save", FileMode.Open);
loadedsave = (Save)bf.ReadObject(file);
file.Close();
scene_has_been_loaded = true;
units = loadedsave.units;
cash = loadedsave.cash;
enemycash = loadedsave.enemy_cash;
SceneManager.LoadScene(loadedsave.scenename);
}
}
我迷路了。更令人困惑的是,只有当AllUnits[]
不为空时,才会出现错误
请检查你是否像你的保存对象那样设置了你的游戏对象可序列化。
你可以试着为你的单位创建一个模型类,它存储了重建游戏对象所需的属性。我不期望GameObject是XmlSerializable的,因为XmlSerializer必须知道要实例化哪个System.Type来填充数组。GameObject是一个抽象类,因此不能实例化。
[DataContract]
public class Unit
{
[DataMember]
public bool IsFriend { get; set; }
[DataMember]
public string Name { get; set; }
}
问题出在这一行:
file.Write(streamer.GetBuffer(), 0, streamer.GetBuffer().Length);
您通常不希望通过getBuffer()
访问流的数据,因为它返回的底层字节数组可能比您写入流中的数据大。
或者使用stream.copyto
方法,如下所示:
streamer.Seek(0, SeekOrigin.Begin); // dont forget to seek to the start of the stream
streamer.CopyTo(file);
或者直接写入文件,根本不使用MemoryStream
:
FileStream file = File.Create(Application.persistentDataPath + "/gamesave.save");
DataContractSerializer bf = new DataContractSerializer(newsave.GetType());
bf.WriteObject(file , newsave);
file.Close();