C# 保存游戏文件的困难
我之所以尝试本教程,是因为我想在XML文件中保存一些数据: 但是我在C# 保存游戏文件的困难,c#,xna,C#,Xna,我之所以尝试本教程,是因为我想在XML文件中保存一些数据: 但是我在SaveGameData类中得到了这个错误消息: IAsyncResult result = device.BeginOpenContainer("StorageDemo", null, null); 命名空间不能直接包含字段或方法等成员 XmlSerializer serializer = new XmlSerializer(typeof(SaveGameData)); 应为类、委托、枚举、接口或结构 怎么了 此外,我不
SaveGameData
类中得到了这个错误消息:
IAsyncResult result = device.BeginOpenContainer("StorageDemo", null, null);
命名空间不能直接包含字段或方法等成员
XmlSerializer serializer = new XmlSerializer(typeof(SaveGameData));
应为类、委托、枚举、接口或结构
怎么了
此外,我不知道如何在文件中写入内容。例如,如果玩家按Escape,我想将分数保存到保存游戏文件中。我该怎么做
public struct SaveGameData
{
public string PlayerName;
public Vector2 AvatarPosition;
public int Level;
public int Score;
}
// Open a storage container.
IAsyncResult result = device.BeginOpenContainer("StorageDemo", null, null);
// Wait for the WaitHandle to become signaled.
result.AsyncWaitHandle.WaitOne();
StorageContainer container = device.EndOpenContainer(result);
// Close the wait handle.
result.AsyncWaitHandle.Close();
string filename = "savegame.sav";
// Check to see whether the save exists.
if (container.FileExists(filename))
// Delete it so that we can create one fresh.
container.DeleteFile(filename);
// Create the file.
Stream stream = container.CreateFile(filename);
// Convert the object to XML data and put it in the stream.
XmlSerializer serializer = new XmlSerializer(typeof(SaveGameData));
serializer.Serialize(stream, data);
// Close the file.
stream.Close();
// Dispose the container, to commit changes.
container.Dispose();
// Open a storage container.
IAsyncResult result =
device.BeginOpenContainer("StorageDemo", null, null);
// Wait for the WaitHandle to become signaled.
result.AsyncWaitHandle.WaitOne();
StorageContainer container = device.EndOpenContainer(result);
// Close the wait handle.
result.AsyncWaitHandle.Close();
string filename = "savegame.sav";
// Check to see whether the save exists.
if (!container.FileExists(filename))
{
// If not, dispose of the container and return.
container.Dispose();
return;
}
// Open the file.
Stream stream = container.OpenFile(filename, FileMode.Open);
XmlSerializer serializer = new XmlSerializer(typeof(SaveGameData));
SaveGameData data = (SaveGameData)serializer.Deserialize(stream);
// Close the file.
stream.Close();
// Dispose the container.
container.Dispose();
你应该把你的代码放在一个方法中,我应该把整个代码放在一个方法中吗?或者只是其中的一部分?除了结构声明之外的所有内容。然后在需要时调用该方法