2
我遇到了我的节约问题的游戏,我已经花了几个小时寻找,没有任何运气的解决方案。我用这个代码写在别人的博客:为什么我不能挽救我在XNA的Xbox 360游戏?
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;
}
}
}
但每当我运行它,我得到这个消息:
类型的未处理的异常“System.InvalidOperationException”发生在Microsoft.Xna.Framework .Storage.dll
附加信息:直到此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();
}
}
但我仍然得到相同的结果。我究竟做错了什么?
太棒了!我试过try和catch和它的工作。现在我可以完美地保存和加载。然而,我在catch块中放入了什么?我不明白这是什么。我知道这是例外,但是什么样的? –
没关系。我找到了它的用处。万分感谢一次收益。 –
不客气,玩得开心! – ChrisO