Orario: 21-05-2013, 5:01 Benvenuto ospite! (Log inRegistrati)


Rispondi 
xna4 x360 save load data
Autore Messaggio
viper
Coder

Messaggi: 48
Registrato: Apr 2010
Offline Offline
#16 RE: xna4 x360 save load data
0
umh...no forse mi sono sbagliato..ho ridato un'occhiata al codice che avevo scritto in passato e uso l'XmlSerializer, anche sull'xbox...quindi...o l'errore circa l'XmlSerializer che ho ricevuto quando ho cercato di buildare era altro (sorry...ma andavo così di fretta che non ho nemmeno visto di cosa si trattava Linguaccia) oppure qualcosa è cambiato dalla v3.1 alla v4.0...ora vediamo..
Ok la soluzione al problema è semplicissima...mancava una reference nel progetto Linguaccia ergo tutto funonzia anche sulla 360, basta soltanto aggiungere la reference (non aggiunta di default) System.Xml.Serialization.

Comunque ci sono delle piccole dimenticanze che creerebbero ancora qualche fastidio sulla 360..il metodo BeginShowSelector richiede sulla console che siano inizializzate le funzionalità Gamer Services PRIMA che tale metodo sia chiamato. Per il resto, tutto funonzia alla grande anche sulla console.

Ecco la "versione 2.0" del suddetto codice...con le opportune modifiche:

Codice:
#region Using Statements
using System;
using System.IO;
using System.Xml.Serialization;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
#endregion Using Statements

namespace TestStorage
{
    #region GameData struct
    /// <summary>
    /// GameData to be serialized/deserialized
    /// </summary>
    public struct GameData
    {
        public int intToSave;
        public string LevelName;
        public bool IsLevelCleared;
    }
    #endregion GameData struct

    #region TestStorageGame
    /// <summary>
    ///
    /// </summary>
    public class TestStorageGame : Game
    {
        #region private fields and constants

        private GraphicsDeviceManager graphics;
        private SpriteBatch spriteBatch;
        private StorageDevice mDevice;

        private GameData LoadedData;

        //Callbacks
        private AsyncCallback mSelectStorageDeviceCallBack;
        private AsyncCallback mOpenContainerCallBack;

        const string fileName = "DATA.txt";
        const string CONTAINER_NAME = "TestContainer";

        #endregion private fields and constants

        #region Constructor
        /// <summary>
        ///
        /// </summary>
        public TestStorageGame()
        {
            this.graphics               = new GraphicsDeviceManager(this);
            this.Content.RootDirectory  = "Content";

#if (XBOX || XBOX360)
            this.Components.Add(new Microsoft.Xna.Framework.GamerServices.GamerServicesComponent(this));
#endif
        }
        #endregion Constructor

        #region Initialize
        /// <summary>
        ///
        /// </summary>
        protected override void Initialize()
        {
            base.Initialize();

            this.mSelectStorageDeviceCallBack   = new AsyncCallback(this.OnStorageDeviceSelected);
            this.mOpenContainerCallBack         = new AsyncCallback(this.OnContainerOpened);

            // Create a new SpriteBatch, which can be used to draw textures.
            this.spriteBatch = new SpriteBatch(GraphicsDevice);

            //base.Initialize MUST be called before SaveGame or LoadGame methods
            //this.LoadGame();
        }
        #endregion Initialize

        #region LoadGame
        /// <summary>
        ///
        /// </summary>
        protected virtual void LoadGame()
        {
            this.ShowStorageDeviceSelector(true);
        }
        #endregion LoadGame

        #region SaveGame
        /// <summary>
        ///
        /// </summary>
        protected virtual void SaveGame()
        {
            this.ShowStorageDeviceSelector(false);
        }
        #endregion SaveGame

        #region ShowStorageDeviceSelector
        /// <summary>
        ///
        /// </summary>
        private void ShowStorageDeviceSelector(bool IsLoading)
        {
            if (this.mSelectStorageDeviceCallBack != null)
            {
                try
                {
                    StorageDevice.BeginShowSelector(PlayerIndex.One, this.mSelectStorageDeviceCallBack, IsLoading);
                }
                catch (Exception ex)
                {
                    string a = "Something went wrong: " + ex.Message;
                }
            }
            else
                throw new ArgumentException("Game must be first initialized!");
        }
        #endregion ShowStorageDeviceSelector

        #region OnStorageDeviceSelected
        /// <summary>
        ///
        /// </summary>
        /// <param name="result"></param>
        private void OnStorageDeviceSelected(IAsyncResult result)
        {
            //Double tap check XD
            if (!result.IsCompleted)
                return;

            try
            {
                this.mDevice = StorageDevice.EndShowSelector(result);

                if (this.mDevice == null)
                {
                    //Maybe no device was selected
                    return;
                }

                if (!this.mDevice.IsConnected)
                {
                    //Do something else when device is NOT connected
                    return;
                }

                this.mDevice.BeginOpenContainer(CONTAINER_NAME, this.mOpenContainerCallBack, result.AsyncState);
            }
            catch (Exception ex)
            {
                string ErrMessage = ex.Message;
                //Do something with your "wonderful" error message
            }
        }
        #endregion OnStorageDeviceSelected

        #region OnContainerOpened
        /// <summary>
        ///
        /// </summary>
        /// <param name="result"></param>
        private void OnContainerOpened(IAsyncResult result)
        {
            if (!result.IsCompleted)
                return;

            try
            {
                StorageContainer container = this.mDevice.EndOpenContainer(result);

                bool isLoading = (bool)result.AsyncState;

                if (isLoading)
                {
                    //Loading Game...
                    if (container.FileExists(fileName))
                    {
                        using (Stream fileStream = container.OpenFile(fileName, FileMode.Open))
                        {
                            XmlSerializer serializer = new XmlSerializer(typeof(GameData));
                            this.LoadedData = (GameData)serializer.Deserialize(fileStream);
                        }
                    }
                }
                else
                {
                    //Saving game..
                    GameData data = new GameData();
                    data.intToSave = 5;
                    data.LevelName = "Level 1 - The beginning";
                    data.IsLevelCleared = false;

                    using (Stream fileStream = container.OpenFile(fileName, FileMode.OpenOrCreate))
                    {
                        XmlSerializer serializer = new XmlSerializer(typeof(GameData));
                        serializer.Serialize(fileStream, data);
                    }
                }

                container.Dispose();
            }
            catch (Exception ex)
            {
                string ErrMessage = ex.Message;
                //Do something with your "wonderful" error message
            }
        }
        #endregion OnContainerOpened

        #region Update
        /// <summary>
        ///
        /// </summary>
        /// <param name="gameTime"></param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            base.Update(gameTime);
        }
        #endregion Update

        #region Draw
        /// <summary>
        ///
        /// </summary>
        /// <param name="gameTime"></param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            spriteBatch.Begin();

            //Draw something nice here XD

            spriteBatch.End();

            base.Draw(gameTime);
        }
        #endregion Draw
    }
    #endregion TestStorageGame
}

Ovviamente, il discorso è differente per quanto riguarda il WP7; lì è necessario "rimpiazzare" StorageDevice e StorageContainer con IsolatedStorage...

Francesco Guastella
(Questo messaggio è stato modificato l'ultima volta il: 27-10-2010 14:32 da viper.)
27-10-2010 14:04
Visita il sito web di questo utente Trova tutti i messaggi di questo utente Cita questo messaggio nella tua risposta
Rispondi 


Vai al forum: