我在保存游戏方面遇到了问题,而且我花了几个小时搜索解决方案而没有任何运气。我使用了这个代码写在某人的博客中:
public class SaveandLoad
{
StorageDevice device;
string containerName = "ChainedWingsContainer";
string filename = "mysave.sav";
public struct SaveGame
{
public int s_mission;
}
public void InitiateSave()
{
if (!Guide.IsVisible)
{
device = null;
StorageDevice.BeginShowSelector(PlayerIndex.One, this.SaveToDevice, null);
}
}
void SaveToDevice(IAsyncResult result)
{
device = StorageDevice.EndShowSelector(result);
if (device != null && device.IsConnected)
{
SaveGame SaveData = new SaveGame()
{
s_mission = Game1.mission,
};
IAsyncResult r = device.BeginOpenContainer(containerName, null, null);
result.AsyncWaitHandle.WaitOne();
StorageContainer container = device.EndOpenContainer(r);
if (container.FileExists(filename))
container.DeleteFile(filename);
Stream stream = container.CreateFile(filename);
XmlSerializer serializer = new XmlSerializer(typeof(SaveGame));
serializer.Serialize(stream, SaveData);
stream.Close();
container.Dispose();
result.AsyncWaitHandle.Close();
}
}
public void InitiateLoad()
{
if (!Guide.IsVisible)
{
device = null;
StorageDevice.BeginShowSelector(PlayerIndex.One, this.LoadFromDevice, null);
}
}
void LoadFromDevice(IAsyncResult result)
{
device = StorageDevice.EndShowSelector(result);
IAsyncResult r = device.BeginOpenContainer(containerName, null, null);
result.AsyncWaitHandle.WaitOne();
StorageContainer container = device.EndOpenContainer(r);
result.AsyncWaitHandle.Close();
if (container.FileExists(filename))
{
Stream stream = container.OpenFile(filename, FileMode.Open);
XmlSerializer serializer = new XmlSerializer(typeof(SaveGame));
SaveGame SaveData = (SaveGame)serializer.Deserialize(stream);
stream.Close();
container.Dispose();
//Update the game based on the save game file
Game1.mission = SaveData.s_mission;
}
}
}
但每当我运行它时,我都会收到此消息:
Microsoft.Xna.Framework.Storage.dll中出现未处理的“System.InvalidOperationException”类型异常
附加信息:在此PlayerIndex使用的所有预先容器已被处置之前,无法打开新容器。
我四处寻找答案,大多数建议建议使用Using语句。所以我使用像这样使用:
void SaveToDevice(IAsyncResult result)
{
device = StorageDevice.EndShowSelector(result);
if (device != null && device.IsConnected)
{
SaveGame SaveData = new SaveGame()
{
s_mission = Game1.mission,
};
IAsyncResult r = device.BeginOpenContainer(containerName, null, null);
result.AsyncWaitHandle.WaitOne();
using (StorageContainer container = device.EndOpenContainer(r))
{
if (container.FileExists(filename))
container.DeleteFile(filename);
Stream stream = container.CreateFile(filename);
XmlSerializer serializer = new XmlSerializer(typeof(SaveGame));
serializer.Serialize(stream, SaveData);
stream.Close();
container.Dispose();
}
result.AsyncWaitHandle.Close();
}
}
但我仍然得到相同的结果。我究竟做错了什么?