• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Spa8nky

[C#] [XML] Serializing/deserializing multiple classes?

11 posts in this topic

How can I serialize/deserialize many different class types using just one XML file?

For example if I have two settings classes, CameraSettings and EnemySettings how can I determine which class I am dealing with when serializing/deserializing their properties using just one XML file?

At the moment when dealing with just one class and I am doing the following for saving:


private void XMLSave(object sender, System.EventArgs e)
{
object currentSettings = Game1.Instance.camera.Settings;

if (currentSettings == null)
{
return;
}

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;

using (XmlWriter xmlWriter = XmlWriter.Create("AllSettings.xml", settings))
{
IntermediateSerializer.Serialize(xmlWriter, currentSettings, null);
}
}




and the following for loading:


private void XMLLoad(object sender, System.EventArgs e)
{
Stream stream = null;
OpenFileDialog openFileDialog = new OpenFileDialog();

openFileDialog.CheckFileExists = true;
openFileDialog.CheckPathExists = true;
openFileDialog.InitialDirectory = "\\";
openFileDialog.Filter = "xml files (*.xml)|*.xml";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;

if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
if ((stream = openFileDialog.OpenFile()) != null)
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = true;

using (XmlReader reader = XmlReader.Create(stream, settings))
{
// - Clear the PhysX scene so no actors and entities are alive
// - Create new entities/actors from settings

Game1.Instance.camera.Settings = IntermediateSerializer.Deserialize<CameraSettings>(reader, null);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}


0

Share this post


Link to post
Share on other sites
I usually just make one top-level class which contains everything I need to deal with and (de)serialize a single instance of that class instead of trying to figure out which is which manually.
0

Share this post


Link to post
Share on other sites
How would that work if I had different settings/properties for different classes?

For example camera settings:

Position
Yaw
Pitch

differ from enemy settings:

Position
Speed
Health

How would I know with one top-level class which one was which?

Apologies for not catching on to what you are saying, I'm a little perplexed by XML at this point.
0

Share this post


Link to post
Share on other sites
Your top level object would look like:

class TopLevel {
CameraSettings camera_settings;
EnemySettings enemy_settings;
}

Just serialize a TopLevel object.
0

Share this post


Link to post
Share on other sites
The .Net serializers will serialize and deserialize entire hierarchies of objects (including proper handling for cyclic references) as long as every object in the hierarchy is serializable. It's pretty awesome.
0

Share this post


Link to post
Share on other sites
Thanks guys.

I guess this means a defined save/load order for settings!

If I am to have my top level class that contains all settings to be saved/loaded, would "get set" accessors be ideal in this scenario when saving/loading settings?

For example with the camera class I could do the following:


public CameraSettings Settings
{
get
{
// If settings class has not been created then create new instance
if (settings == null)
{
settings = new CameraSettings();
}

// Write the necessary camera properties to the settings data
// Settings should only be called when saving
settings.Position = position;

return settings;
}
set
{
// Assign the new settings
settings = value;

// Change the camera properties based on the settings
Position = settings.Position;
}
}





Or would you recommend a different approach?

EDIT: Thinking about this some more, would it be better to just overwrite the existing camera (if there is one) by creating a new camera instance when the data is loaded? Or should I only do this if a camera instance has not been created?

[Edited by - Spa8nky on June 11, 2010 7:41:20 AM]
0

Share this post


Link to post
Share on other sites
I'm only use the top level class as a *temporary* for (de)serialization, since it doesn't really provide any useful purpose other than that.
0

Share this post


Link to post
Share on other sites
What do you think of the following idea?

I create a *temp* SaveData class that can hold any settings class that derives from an abstract settings class:


[Serializable]
class SaveData
{
List<Settings> settings = new List<Settings>(100);

public SaveData() { }

public void Load()
{
for (int i = 0; i < settings.Count; ++i)
{
settings[i].Load();
}
}

public void Save()
{
for (int i = 0; i < settings.Count; ++i)
{
settings[i].Save();
}
}

public List<Settings> AllSettings
{
get { return settings; }
set { settings = value; }
}
}



The base settings class looks like the following:


public abstract class Settings
{
public abstract void Load();
public abstract void Save();
}



and a derived camera settings class will look like this:


[Serializable]
public class CameraSettings : Settings
{
public float FarClip = 1000.0f;
public float NearClip = 0.1f;
public float Pitch = 0.0f; // Pitch (radians)
public Vector3 Position = Vector3.Zero;
public float Sensitivity = 0.3f;
public float Yaw = 0.0f; // Yaw (radians)

[NonSerialized]
Camera camera;

public CameraSettings() { }

// Constructor requires associated camera
public CameraSettings(Camera camera)
{
this.camera = camera;
}

public override void Load()
{
Game1.Instance.camera = new Camera_FreeLook(this);
}

public override void Save()
{
FarClip = camera.FarClip;
NearClip = camera.NearClip;
Pitch = (float)Math.Asin(camera.ViewMatrix.M23);
Position = camera.Position;
Sensitivity = camera.LookSensitivity;
Yaw = (float)Math.Atan2(camera.ViewMatrix.M13, camera.ViewMatrix.M33);
}
}



The SaveData class can now be used for saving and loading any settings class by doing the following:


private void XMLLoad(object sender, System.EventArgs e)
{
Stream stream = null;
OpenFileDialog openFileDialog = new OpenFileDialog();

openFileDialog.CheckFileExists = true;
openFileDialog.CheckPathExists = true;
openFileDialog.InitialDirectory = "\\";
openFileDialog.Filter = "xml files (*.xml)|*.xml";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;

if (openFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
if ((stream = openFileDialog.OpenFile()) != null)
{
XmlReaderSettings settings = new XmlReaderSettings();
settings.IgnoreComments = true;

using (XmlReader reader = XmlReader.Create(stream, settings))
{
// - Clear the PhysX scene so no actors and entities are alive
// - Create new entities/actors from settings
SaveData saveData = IntermediateSerializer.Deserialize<SaveData>(reader, null);
saveData.Load();
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}

private void XMLSave(object sender, System.EventArgs e)
{
SaveData saveData = new SaveData();
saveData.AllSettings.Add(Game1.Instance.camera.Settings);
saveData.Save();

XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;

using (XmlWriter xmlWriter = XmlWriter.Create("AllSettings.xml", settings))
{
IntermediateSerializer.Serialize(xmlWriter, saveData, null);
}
}



What are your opinions on this approach? Have creating something hellish or is this a sensible idea?
0

Share this post


Link to post
Share on other sites
I think you're seriously overthinking this. What value does a base settings class add over just making your individual settings classes serializable? If you lose the type information of dumping all the settings objects into a list, how are you going to get them stuck back into the right places?
0

Share this post


Link to post
Share on other sites
Quote:

If you lose the type information of dumping all the settings objects into a list, how are you going to get them stuck back into the right places?


I was thinking along the lines of flexibility. Are you saying just keep it simple and only serialize/deserialize definite classes in a definite order?
0

Share this post


Link to post
Share on other sites
This is more flexible how? What does any of that extra code actually gain you?
0

Share this post


Link to post
Share on other sites
I'm guessing little to nothing. It was an attempt to save/load settings automatically using the overriding methods.

Is there no way to do this non-explicitly then?
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0