11 Replies - 1140 Views - Last Post: 28 March 2011 - 03:16 PM

#1 ShadowsEdge19  Icon User is offline

  • D.I.C Addict

Reputation: 142
  • View blog
  • Posts: 664
  • Joined: 16-January 10

Loading serialized data from another project help

Posted 28 March 2011 - 04:02 AM

As you all know I made a Level Editor program in order to create level files that would be used by my main game project. Now I've started to make my game and got as far as being able to incorporate the data that should be obtained by the file but I can't access it because I get an error trying to access save data from another project without a connection to the LevelEditor Assembly:

Unable to find assembly 'BlockableLevelEditor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.

Which comes up when it runs this line with a file matching the fileName:

SaveGameData data = (SaveGameData)formatter.Deserialize(stream);

Now at the moment I start the program off by loading the gameplayscreen with a level no. and I load the data from the saved file before the Load Content occurs otherwise I will get an error, at the moment I've had to link to the LoadLevel() method before it starts to load all the other game content:

        /// <summary>
        /// Constructor.
        /// </summary>
        public GameplayScreen(int levelNo)
        {
            TransitionOnTime = TimeSpan.FromSeconds(1.5);
            TransitionOffTime = TimeSpan.FromSeconds(0.5);
            blockableGame = new BlockableGame();
            gameLevel = new Level();
            currentLevelNo = levelNo;

            stateobj = (Object)"GetDevice for Player One";

            StorageDevice.BeginShowSelector(PlayerIndex.One, this.GetDevice, stateobj);

            result = StorageDevice.BeginShowSelector(
                                PlayerIndex.One, null, null);

            StorageDevice device = StorageDevice.EndShowSelector(result);

            if (device != null && device.IsConnected)
            {
                LoadLevel(device, currentLevelNo);
            }

            HandleGame();
        }

        /// <summary>
        /// Load graphics content for the game.
        /// </summary>
        public override void LoadContent()
        {
            if (content == null)
                content = new ContentManager(ScreenManager.Game.Services, "Content");

            gameFont = content.Load<SpriteFont>("gamefont");

            gameLevel.LoadContent(content);

            // A real game would probably have more content than this sample, so
            // it would take longer to load. We simulate that by delaying for a
            // while, giving you a chance to admire the beautiful loading screen.
            Thread.Sleep(1000);

            // once the load has finished, we use ResetElapsedTime to tell the game's
            // timing mechanism that we have just finished a very long frame, and that
            // it should not try to catch up.
            ScreenManager.Game.ResetElapsedTime();
        }

       void GetDevice(IAsyncResult result)
        {
            device = StorageDevice.EndShowSelector(result);
        }

        public void LoadLevel(StorageDevice device, int levelNo)
        {
            string fileName;

            fileName = string.Format("level{0}.sav", levelNo);

            // Open a storage container.
            IAsyncResult result =
                device.BeginOpenContainer("BlockableFiles", null, null);

            // Wait for the WaitHandle to become signaled.
            result.AsyncWaitHandle.WaitOne();

            StorageContainer container = device.EndOpenContainer(result);

            // Close the wait handle.
            result.AsyncWaitHandle.Close();

            // 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);

            // Read the data from the file.
            BinaryFormatter formatter = new BinaryFormatter();

            SaveGameData data = (SaveGameData)formatter.Deserialize(stream);

            // Close the file.
            stream.Close();

            // Dispose the container.
            container.Dispose();

            for (int i = 0; i < gameLevel.DataHeight; i++)
            {
                for (int j = 0; j < gameLevel.DataWidth; j++)
                {
                    gameLevel.Grid[i, j] = new Tile(data.gameGrid[i, j], i, j);
                }
            }
        }


This post has been edited by ShadowsEdge19: 28 March 2011 - 06:37 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Loading serialized data from another project help

#2 Robin19  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 272
  • View blog
  • Posts: 552
  • Joined: 07-July 10

Re: Loading serialized data from another project help

Posted 28 March 2011 - 08:33 AM

Where is SaveGameData Class located? That error suggests you don't have a reference set up properly.

Are you using the LevelEditor's SaveGameData or did you make a new SaveGameData?
Was This Post Helpful? 0
  • +
  • -

#3 ShadowsEdge19  Icon User is offline

  • D.I.C Addict

Reputation: 142
  • View blog
  • Posts: 664
  • Joined: 16-January 10

Re: Loading serialized data from another project help

Posted 28 March 2011 - 08:38 AM

I've used the exact same SaveGameData structure as in LevelEditor:

[Serializable]
public struct SaveGameData
{
    public int[,] gameGrid;
}


It's located in the fields section of GamePlayScreen.

This post has been edited by ShadowsEdge19: 28 March 2011 - 08:42 AM

Was This Post Helpful? 0
  • +
  • -

#4 Robin19  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 272
  • View blog
  • Posts: 552
  • Joined: 07-July 10

Re: Loading serialized data from another project help

Posted 28 March 2011 - 08:47 AM

I don't think same will be good enough. I know I had this problem when deserializing from a web service. Although you call it the same and they are built the same, C#(CLI?) knows they are different and refuses to treat them the same. You need to reference the level editor and use that SaveGameData. The better option is to create another project that contains SaveGameData. Both the level editor and the game can reference that DLL. This will require you to recreate the xml.

Just curious, could you post the xml header?
Was This Post Helpful? 0
  • +
  • -

#5 ShadowsEdge19  Icon User is offline

  • D.I.C Addict

Reputation: 142
  • View blog
  • Posts: 664
  • Joined: 16-January 10

Re: Loading serialized data from another project help

Posted 28 March 2011 - 09:00 AM

Here's is the GameplayScreen stuff that deals with the Loading in the main game project:
using System;
using System.Threading;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml.Serialization;
using System.IO;
using System.Diagnostics;
#endregion

namespace Blockable
{
    /// <summary>
    /// This screen implements the actual game logic. It is just a
    /// placeholder to get the idea across: you'll probably want to
    /// put some more interesting gameplay in here!
    /// </summary>
    class GameplayScreen : GameScreen
    {
        #region Fields

        ContentManager content;
        Level gameLevel;
        int currentLevelNo;

        StorageDevice device;
        IAsyncResult result;
        Object stateobj;

        enum GamePhase
        { 
            SelectingCrate,
            MovingCrate,
            MidLevel,
            GameOver
        }

        [Serializable]
        public struct SaveGameData
        {
            public int[,] gameGrid;
        }

        #endregion

        #region Initialization

        /// <summary>
        /// Constructor.
        /// </summary>
        public GameplayScreen(int levelNo)
        {
            TransitionOnTime = TimeSpan.FromSeconds(1.5);
            TransitionOffTime = TimeSpan.FromSeconds(0.5);
            blockableGame = new BlockableGame();
            gameLevel = new Level();
            currentLevelNo = levelNo;

            stateobj = (Object)"GetDevice for Player One";

            StorageDevice.BeginShowSelector(PlayerIndex.One, this.GetDevice, stateobj);

            result = StorageDevice.BeginShowSelector(
                                PlayerIndex.One, null, null);

            StorageDevice device = StorageDevice.EndShowSelector(result);

            if (device != null && device.IsConnected)
            {
                LoadLevel(device, currentLevelNo);
            }
        }

        void GetDevice(IAsyncResult result)
        {
            device = StorageDevice.EndShowSelector(result);
        }

        public void LoadLevel(StorageDevice device, int levelNo)
        {
            string fileName;

            fileName = string.Format("level{0}.sav", levelNo);

            // Open a storage container.
            IAsyncResult result =
                device.BeginOpenContainer("BlockableFiles", null, null);

            // Wait for the WaitHandle to become signaled.
            result.AsyncWaitHandle.WaitOne();

            StorageContainer container = device.EndOpenContainer(result);

            // Close the wait handle.
            result.AsyncWaitHandle.Close();

            // 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);

            // Read the data from the file.
            BinaryFormatter formatter = new BinaryFormatter();

            SaveGameData data = new SaveGameData();
            data.gameGrid = new int[10, 10];

            data = (SaveGameData)formatter.Deserialize(stream);

            // Close the file.
            stream.Close();

            // Dispose the container.
            container.Dispose();

            for (int i = 0; i < gameLevel.DataHeight; i++)
            {
                for (int j = 0; j < gameLevel.DataWidth; j++)
                {
                    gameLevel.Grid[i, j] = new Tile(data.gameGrid[i, j], i, j);
                }
            }
        }



Here is the main screen class of the LevelEditor project that contains the saving and loading:

using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Storage;
using System.Xml.Serialization;
using System.IO;
using System.Diagnostics;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace BlockableLevelEditor
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class LevelEditor : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        Texture2D blank;

        List<Tile> texButtons;
        List<File> fileButtons;

        LevelGrid levelGrid;

        Texture2D levelBarrier;

        SpriteFont fileNameFont;

        int selectedButtonIndex;
        bool buttonselected;

        string selectedFilename;
        int selectedFileIndex;
        bool fileSelected;

        Button newLevelButton;
        Button saveLevelButton;
        Button loadLevelButton;
        Button deleteLevelButton;

        bool aPressed = false;
        bool gameSaveRequested = false;
        bool gameLoadRequested = false;
        bool gameDeleteRequested = false;
        bool getFileNamesRequest = false;

        string[] fileNames;

        private GamePadState oldGamepadState;
        private MouseState currentMouseState;
        private MouseState lastMouseState;

        StorageDevice device;
        IAsyncResult result;
        Object stateobj;

        [Serializable]
        public struct SaveGameData
        {
            public int[,] gameGrid;
        }

        #region Level Editor Constructor

        public LevelEditor()
        {
            graphics = new GraphicsDeviceManager(this);

            graphics.PreferredBackBufferWidth = 1024;
            graphics.PreferredBackBufferHeight = 680;
            graphics.PreferMultiSampling = false;

            window.AllowUserResizing = true;

            Mouse.WindowHandle = this.window.Handle;
            this.IsMouseVisible = true;

            levelGrid = new LevelGrid();

            texButtons = new List<Tile>();
            fileButtons = new List<File>();

            // Change to 9 when all textures are made
            for (int i = 0; i < 15; i++)
            {
                texButtons.Add(new Tile(i, true));
            }

            newLevelButton = new Button(new Vector2(675, 630));
            saveLevelButton = new Button(new Vector2(760, 630));
            loadLevelButton = new Button(new Vector2(845, 630));
            deleteLevelButton = new Button(new Vector2(930, 630));

            Content.RootDirectory = "Content";

            currentMouseState = new MouseState();
            lastMouseState = new MouseState();

            // Reset the device
            device = null;
            stateobj = (Object)"GetDevice for Player One";
            StorageDevice.BeginShowSelector(PlayerIndex.One, this.GetDevice, stateobj);

            getFileNamesRequest = true;
            result = StorageDevice.BeginShowSelector(
                                PlayerIndex.One, null, null);

            StartProgram(false);
        }

        #endregion

        #region Initialize
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            base.Initialize();
        }

        #endregion

        #region Load Content
        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            newLevelButton.LoadContent(Content);
            saveLevelButton.LoadContent(Content);
            loadLevelButton.LoadContent(Content);
            deleteLevelButton.LoadContent(Content);

            blank = Content.Load<Texture2D>("blank");
            levelBarrier = Content.Load<Texture2D>("LevelBarrier");
            fileNameFont = Content.Load<SpriteFont>("normalFont");

            for (int i = 0; i < levelGrid.DataHeight; i++)
            {
                for (int j = 0; j < levelGrid.DataWidth; j++)
                {
                    levelGrid.Grid[i, j].LoadContent(Content);
                }
            }

            foreach (Tile t in texButtons)
            {
                t.LoadContent(Content);
            }

            foreach (File f in fileButtons)
            {
                f.LoadContent(Content);
            }
        }

        #endregion

        #region Unload Content

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            Content.Unload();
        }

        #endregion

        #region Start Program

        public void StartProgram(bool reset)
        {
            for(int i = 0; i < levelGrid.DataHeight; i++)
            {
                for (int j = 0; j < levelGrid.DataWidth; j++)
                {  
                    levelGrid.Grid[i, j] = new Tile(0,false);
                }
            }
            if (reset)
            {
                buttonselected = false;
                texButtons[selectedButtonIndex].Selected = false;
                fileSelected = false;
                fileButtons[selectedFileIndex].Selected = false;

                UnloadContent();
                LoadContent();
            }
        }

        #endregion
        
        void GetDevice(IAsyncResult result)
        {
            device = StorageDevice.EndShowSelector(result);
        }

        #region Save Level

        public void SaveLevel(StorageDevice device)
        {
            int n = 0;
            string filename;
            // Create the data to save.
            SaveGameData data = new SaveGameData();
            data.gameGrid = new int[10, 10];

            for (int i = 0; i < levelGrid.DataHeight; i++)
            {
                for (int j = 0; j < levelGrid.DataWidth; j++)
                {
                    data.gameGrid[i,j] = levelGrid.Grid[i,j].TexNo;
                }
            }

            // Open a storage container.
            IAsyncResult result =
                device.BeginOpenContainer("BlockableFiles", null, null);

            // Wait for the WaitHandle to become signaled.
            result.AsyncWaitHandle.WaitOne();

            StorageContainer container = device.EndOpenContainer(result);

            // Close the wait handle.
            result.AsyncWaitHandle.Close();

            if (fileSelected)
            {
                filename = selectedFilename;
                fileButtons[selectedFileIndex].Selected = false;
                fileSelected = false;
            }
            else
            {
                while (container.FileExists("level" + n + ".sav"))
                {
                    n++;
                }

                filename = "level" + n + ".sav";
            }

            // Create the file.
            Stream stream = container.CreateFile(filename);

            BinaryFormatter formatter = new BinaryFormatter();

            formatter.Serialize(stream, data);

            // Close the file.
            stream.Close();

            // Dispose the container, to commit changes.
            container.Dispose();

            // Set the request flag
            if (getFileNamesRequest == false)
            {
                getFileNamesRequest = true;
                result = StorageDevice.BeginShowSelector(
                        PlayerIndex.One, null, null);
            }
        }

        #endregion

        #region Load Level

        /// <summary>
        /// This method loads a serialized data object
        /// from the StorageContainer for this game.
        /// </summary>
        /// <param name="device"></param>
        private void LoadLevel(StorageDevice device)
        {
            // Open a storage container.
            IAsyncResult result =
                device.BeginOpenContainer("BlockableFiles", 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 = string.Format(selectedFilename);

            // 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);

            // Read the data from the file.
            BinaryFormatter formatter = new BinaryFormatter();
          
            SaveGameData data = (SaveGameData)formatter.Deserialize(stream);

            // Close the file.
            stream.Close();

            // Dispose the container.
            container.Dispose();

            for (int i = 0; i < levelGrid.DataHeight; i++)
            {
                for (int j = 0; j < levelGrid.DataWidth; j++)
                {
                    levelGrid.Grid[i, j] = new Tile(data.gameGrid[i,j],false);
                }
            }

            UnloadContent();
            LoadContent();
        }

        #endregion

        #region Delete File

        /// <summary>
        /// This method deletes a file previously created by this demo.
        /// </summary>
        /// <param name="device"></param>
        public void DeleteLevel(StorageDevice device)
        {
            IAsyncResult result =
                device.BeginOpenContainer("StorageDemo", null, null);

            // Wait for the WaitHandle to become signaled.
            result.AsyncWaitHandle.WaitOne();

            String fileName = selectedFilename; 

            StorageContainer container = device.EndOpenContainer(result);

            // Close the wait handle.
            result.AsyncWaitHandle.Close();

            if (container.FileExists(fileName))
            {
                fileName = selectedFilename;
                fileButtons[selectedFileIndex].Selected = false;
                fileSelected = false;
                container.DeleteFile(fileName);
            }

            // Set the request flag
            if (getFileNamesRequest == false)
            {
                getFileNamesRequest = true;
                result = StorageDevice.BeginShowSelector(
                        PlayerIndex.One, null, null);
            }

            // Dispose the container, to commit the change.
            container.Dispose();
        }

        #endregion

        #region Get File Names

        public void GetFileNames()
        {
            // Open a storage container.
            IAsyncResult result =
                device.BeginOpenContainer("BlockableFiles", null, null);

            // Wait for the WaitHandle to become signaled.
            result.AsyncWaitHandle.WaitOne();

            StorageContainer container = device.EndOpenContainer(result);
            
            fileNames = container.GetFileNames();
            fileButtons.Clear();

            // Close the wait handle.
            result.AsyncWaitHandle.Close();

            // Dispose the container, to commit changes.
            container.Dispose();

            foreach (string s in fileNames)
            { 
                fileButtons.Add(new File(s));
            }
        }

        #endregion

        #region Update

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

            GamePadState pad = GamePad.GetState(PlayerIndex.One);
            aPressed = (pad.Buttons.A == ButtonState.Pressed && pad.Buttons.A != oldGamepadState.Buttons.A);
            oldGamepadState = pad;
      
            //Updates the previous mouse state;
            lastMouseState = currentMouseState;

            //Updates to the newest mouse state
            currentMouseState = Mouse.GetState();

            newLevelButton.Update();
            saveLevelButton.Update();
            loadLevelButton.Update();
            deleteLevelButton.Update();

            //Deal with the user input
            HandleInput();

            // If a save is pending, save as soon as the
            // storage device is chosen
            if ((gameSaveRequested) && (result.IsCompleted))
            {
                StorageDevice device = StorageDevice.EndShowSelector(result);
                if (device != null && device.IsConnected)
                {
                    SaveLevel(device);
                }
                // Reset the request flag
                gameSaveRequested = false;
            }

            // If a load is pending, load as soon as the
            // storage device is chosen
            if ((gameLoadRequested) && (result.IsCompleted))
            {
                StorageDevice device = StorageDevice.EndShowSelector(result);
                if (device != null && device.IsConnected)
                {
                    LoadLevel(device);
                }
                // Reset the request flag
                gameLoadRequested = false;
            }

            // If a deletion is pending, delete as soon as the
            // storage device is chosen
            if ((gameDeleteRequested) && (result.IsCompleted))
            {
                StorageDevice device = StorageDevice.EndShowSelector(result);
                if (device != null && device.IsConnected)
                {
                    DeleteLevel(device);
                }
                // Reset the request flag
                gameDeleteRequested = false;
            }

            // If a request for file names is pending, obtain them
            // as soon as the storage device is chosen
            if ((getFileNamesRequest) && (result.IsCompleted))
            {
                GetFileNames();
                // Reset the request flag
                getFileNamesRequest = false;
            }

            LoadContent();
        }

        #endregion

        #region Handle Input

        public void HandleInput()
        {
            MouseState mouse = Mouse.GetState();
            
            Tile newTile;

            for (int i = 0; i < texButtons.Count; i++)
            {
                if (texButtons[i].Bounds.Contains(mouse.X, mouse.Y))
                {
                    if ((currentMouseState.LeftButton == ButtonState.Released
                        && lastMouseState.LeftButton == ButtonState.Pressed) || aPressed)
                    {
                        if (buttonselected)
                        {
                            if(i == selectedButtonIndex)
                            {
                                buttonselected = false;
                                texButtons[i].Selected = false;
                            }
                            else
                            {
                                buttonselected = true;
                                texButtons[selectedButtonIndex].Selected = false;
                                selectedButtonIndex = i;
                                texButtons[i].Selected = true;
                            }
                        }
                        else 
                        {
                            buttonselected = true;
                            selectedButtonIndex = i;
                            texButtons[i].Selected = true;
                        }
                    }
                }
            }

            
            for (int i = 0; i < fileButtons.Count; i++)
            {
                if (fileButtons[i].Bounds.Contains(mouse.X, mouse.Y))
                {
                    if ((currentMouseState.LeftButton == ButtonState.Released
                        && lastMouseState.LeftButton == ButtonState.Pressed) || aPressed)
                    {
                        if (fileSelected)
                        {
                            if (i == selectedFileIndex)
                            {
                                fileSelected = false;
                                fileButtons[i].Selected = false;
                            }
                            else
                            {
                                fileSelected = true;
                                fileButtons[selectedFileIndex].Selected = false;
                                selectedFileIndex = i;
                                selectedFilename = fileButtons[i].FileName;
                                fileButtons[i].Selected = true;
                            }
                        }
                        else
                        {
                            fileSelected = true;
                            selectedFileIndex = i;
                            fileButtons[i].Selected = true;
                            selectedFilename = fileButtons[i].FileName;
                        }
                    }
                }
            }

            if (buttonselected)
            {
                for (int i = 0; i < levelGrid.DataHeight; i++)
                {
                    for (int j = 0; j < levelGrid.DataWidth; j++)
                    {
                        if (levelGrid.Grid[i,j].Bounds.Contains(mouse.X, mouse.Y))
                        {
                            if ((currentMouseState.LeftButton == ButtonState.Released
                                    && lastMouseState.LeftButton == ButtonState.Pressed) || aPressed)
                            {
                                newTile = new Tile(selectedButtonIndex, false);
                                levelGrid.Grid[i, j] = newTile;
                                levelGrid.Grid[i, j].LoadContent(Content);
                            }
                        }
                    }
                }
            }
            

            #region New Level Button

            if ((newLevelButton.Bounds.Contains(mouse.X, mouse.Y)) || aPressed)
            {
                    // Was the button pressed?
                if ((currentMouseState.LeftButton == ButtonState.Released &&
                       lastMouseState.LeftButton == ButtonState.Pressed) || aPressed)
                {
                    StartProgram(true);
                }
            }

            #endregion

            #region Save Level Button

            if ((saveLevelButton.Bounds.Contains(mouse.X, mouse.Y)) || aPressed)
            {
                // Was the button pressed?
                if (currentMouseState.LeftButton == ButtonState.Released &&
                   lastMouseState.LeftButton == ButtonState.Pressed)
                {

                    // Set the request flag
                    if (gameSaveRequested == false)
                    {
                        gameSaveRequested = true;
                        result = StorageDevice.BeginShowSelector(
                                PlayerIndex.One, null, null);
                    }
                }
            }

            #endregion   

            #region Load Level Button

            if ((loadLevelButton.Bounds.Contains(mouse.X, mouse.Y)) || aPressed)
            {
                // Was the button pressed?
                if (currentMouseState.LeftButton == ButtonState.Released &&
                   lastMouseState.LeftButton == ButtonState.Pressed)
                {
                    if (fileSelected)
                    {
                        // Set the request flag
                        if (gameLoadRequested == false)
                        {
                            gameLoadRequested = true;
                            result = StorageDevice.BeginShowSelector(
                                    PlayerIndex.One, null, null);
                        }
                    }
                }
            }

            #endregion

            #region Delete Level Button

            if ((deleteLevelButton.Bounds.Contains(mouse.X, mouse.Y)) || aPressed)
            {
                // Was the button pressed?
                if (currentMouseState.LeftButton == ButtonState.Released &&
                   lastMouseState.LeftButton == ButtonState.Pressed)
                {
                    if (fileSelected)
                    {
                        // Set the request flag
                        if (gameDeleteRequested == false)
                        {
                            gameDeleteRequested = true;
                            result = StorageDevice.BeginShowSelector(
                                    PlayerIndex.One, null, null);
                        }
                    }
                }
            }

            #endregion   
        }

        #endregion
    }
}


This post has been edited by ShadowsEdge19: 28 March 2011 - 09:01 AM

Was This Post Helpful? 0
  • +
  • -

#6 lesPaul456  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 173
  • View blog
  • Posts: 729
  • Joined: 16-April 09

Re: Loading serialized data from another project help

Posted 28 March 2011 - 10:31 AM

As Robin19 said, don't recreate the SaveGameData struct. I would suggest creating a new assembky that contains the SaveGameData struct, and reference it from both the level editor and the game. You could also add a reference to the level editor assembly from the game.

Another option is to create a custom SerializationBinder.
Was This Post Helpful? 0
  • +
  • -

#7 ShadowsEdge19  Icon User is offline

  • D.I.C Addict

Reputation: 142
  • View blog
  • Posts: 664
  • Joined: 16-January 10

Re: Loading serialized data from another project help

Posted 28 March 2011 - 10:51 AM

View PostlesPaul456, on 28 March 2011 - 10:31 AM, said:

As Robin19 said, don't recreate the SaveGameData struct. I would suggest creating a new assembky that contains the SaveGameData struct, and reference it from both the level editor and the game. You could also add a reference to the level editor assembly from the game.

Another option is to create a custom SerializationBinder.


Could you please provide an example of the former? I'm not sure what you are asking me to do.
Was This Post Helpful? 0
  • +
  • -

#8 lesPaul456  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 173
  • View blog
  • Posts: 729
  • Joined: 16-April 09

Re: Loading serialized data from another project help

Posted 28 March 2011 - 11:39 AM

There's an example of how to use the SerializationBinder on the page I linked. Basically, create a class that derives from SerializationBinder and override the BindToType method.

I'd probably just create a new project that contains the SaveGameData struct and reference it from both the level editor and the game, though: How To: Add or Remove References in Visual Studio, Project References.
Was This Post Helpful? 0
  • +
  • -

#9 ShadowsEdge19  Icon User is offline

  • D.I.C Addict

Reputation: 142
  • View blog
  • Posts: 664
  • Joined: 16-January 10

Re: Loading serialized data from another project help

Posted 28 March 2011 - 12:45 PM

When I create a new Project should I just put the Structure in the Program.cs class or the ProjectName.cs class and leave it at that?
Was This Post Helpful? 0
  • +
  • -

#10 lesPaul456  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 173
  • View blog
  • Posts: 729
  • Joined: 16-April 09

Re: Loading serialized data from another project help

Posted 28 March 2011 - 01:42 PM

It's pretty straight forward.

First, get rid of the SaveGameData from the level editor and the game.

Right click on the solution from the solution explorer and select "Add->New Project". Select the ClassLibrary template.

The new project will be generated, and "Class1.cs" will be created. Right click "Class1.cs" from the solution explorer and select rename. Rename it to "SaveGameData.cs". Open that file, and edit it to match your SaveGameData struct.

Now, go to the level editor project, right click References and select "Add Reference...". If the Projects tab is not selected, select it and then select the project you just created and press "OK".

Do the same thing to add the reference to your game's project.

Don't forget that to use the SaveGameData struct, you'll have to add the namespace to the using directives.
Was This Post Helpful? 1
  • +
  • -

#11 ShadowsEdge19  Icon User is offline

  • D.I.C Addict

Reputation: 142
  • View blog
  • Posts: 664
  • Joined: 16-January 10

Re: Loading serialized data from another project help

Posted 28 March 2011 - 03:02 PM

I've linked both projects to the SaveGameData project and added References to each but I'm still not getting it to use the namespace properly:

Here's the SaveGameData.cs from the ClassLibrary project:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SaveGameData
{
    public class SaveGameData
    {
        [Serializable]
        int[,] gameGrid;

        public SaveGameData()
        {
            gameGrid = new int[10, 10];
        }
    }
}



I've added "using SaveGameData;" to LevelEditor's main class and with the project reference works fine.

But I'm not certain whether I've made the SaveGameData class correctly or I'm just not using it right in the SaveLevel() of LevelEditor:

        public void SaveLevel(StorageDevice device)
        {
            int n = 0;
            string filename;
            // Create the data to save.
            SaveGameData.SaveGameData data = new SaveGameData.SaveGameData();

            for (int i = 0; i < levelGrid.DataHeight; i++)
            {
                for (int j = 0; j < levelGrid.DataWidth; j++)
                {
                    data[i,j] = levelGrid.Grid[i,j].TexNo;
                }
            }
....
}



I get this errors:

Error 1 Cannot apply indexing with [] to an expression of type

Edit: Nevermind I've fixed the error, firstly I didn't put a public declaration on int[,] gameGrid so I couldn't access that in LevelEditor.

This post has been edited by ShadowsEdge19: 28 March 2011 - 03:08 PM

Was This Post Helpful? 0
  • +
  • -

#12 ShadowsEdge19  Icon User is offline

  • D.I.C Addict

Reputation: 142
  • View blog
  • Posts: 664
  • Joined: 16-January 10

Re: Loading serialized data from another project help

Posted 28 March 2011 - 03:16 PM

I've got it fully integrated into both projects and I can load and save files from each into a single SavedGame content folder which is an added bonus. Awesome :D
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1