保存游戏文件的困难

时间:2012-12-20 17:41:08

标签: c# xna

我正在尝试本教程,因为我想在XML文件中保存一些数据:http://msdn.microsoft.com/en-us/library/bb203924.aspx

但我在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();

0 个答案:

没有答案