I am trying to serialize my game data. In case the user presses the Windows button, everything should be saved. I know that we should override the OnExiting event in the game class. but am using the Game State Management , I want to serialize game data in my GamePlayScreen class. I did override the Serialize and DeSerialize methods, but they didnt work.
hers my code:
public override void Serialize(Stream stream)
{
gameState.HumanPlayer = HumanPlayer;
gameState.Player1 = AIPlayer1;
gameState.Player2 = AIPlayer2;
gameState.Player3 = AIPlayer3;
XmlSerializer serializer = new XmlSerializer(typeof(GameState));
serializer.Serialize(stream, gameState);
base.Serialize(stream);
}
public override void Deserialize(Stream stream)
{
XmlSerializer serializer = new XmlSerializer(typeof(GameState));
gameState = (GameState)serializer.Deserialize(stream);
if (gameState.HumanPlayer != null)
HumanPlayer = gameState.HumanPlayer;
if (gameState.Player1 != null)
AIPlayer1 = gameState.Player1;
if (gameState.Player2 != null)
AIPlayer2 = gameState.Player2;
if (gameState.Player3 != null)
AIPlayer3 = gameState.Player3;
base.Deserialize(stream);
}
I tried to create my own IsolatedStorageFile instead of the provided stream object, but it didnt work.
I tried to write the same code in the Load and Unload event. it works fine there, but in case of pressing the back button. i need to serialize if the user pressed the windows button or the search button.
It looks like you need to handle the
OnDeactivatedandOnActivatedevents. Just do the same thing as is done in theOnExitingevent and the Constructor. I would have thought the sample would do this as proper handling of tombstone/rehydrate is such a big thing for WP7, however it seems it has been neglected. Note thatOnActivatedis NOT called when the app is launched andOnDeactivatedis NOT called when the app is closed manually or exited using the Back button.Note that
ActivatedandDeactivatedarea also available as events onPhonApplicationServices.Current, along withLaunchingandClosing, which are ONLY called on actual open and exit situations.EDIT
Ok, I take it back.
OnDeactivatedandOnActivatedare not required. It seems that OnExiting is fired for both Deactivate and Exit scenarios. I downloaded the sample you linked (XNA4 WP7, not Mango version) and put this code into theGameplayScreen:A break point shows that the Deserialize method is being hit functioning correctly, so your problem must be in how you apply your loaded data, or perhaps you’ve edited other code that has broken it.