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