Game Development Reference
In-Depth Information
Getting Started with XML: Serialization
There are two main methods for saving data to XML in Unity using the Mono Framework classes.
One method (the manual method) is to create an XML file in code, node by node, through looping
and iteration, saving each element of data as nodes are created, using a class such as XmlDocument .
The other method (used here) is to use serialization through the XMLSerializer class. By using
serialization, you may effectively stream or snapshot a class in memory, translate it to a text-based
XML version, and then write it to a persistent fileā€”one that can be accessed later in other gaming
sessions to automatically rebuild the class that was saved. Thus, by consolidating all save-game
data into a single class, we can create a save-game state quickly and effectively. This method
can spare us a lot of coding and extra work, but it only works with specific data types (and not all
data types). This means that, before we can work with serialization itself, we'll need to code some
new custom classes and structures to hold all game data, but using only data types supported by
serialization. We'll then need to populate this class with valid game data prior to saving to ensure
that all appropriate data is saved. Listing 9-4 lists a new LoadSaveManager class created in the file
LoadSaveManager.cs . This file includes new serializable classes and structures that can be saved to
an XML file.
Listing 9-4. Starting a LoadSaveManager Class
01 //Loads and Saves game state data to and from xml file
02 //-----------------------------------------------
03 using UnityEngine;
04 using System.Collections;
05 using System.Collections.Generic;
06 using System.Xml;
07 using System.Xml.Serialization;
08 using System.IO;
09 //-----------------------------------------------
10 public class LoadSaveManager : MonoBehaviour
11 {
12 //Save game data
13 [XmlRoot("GameData")]
14 public class GameStateData
15 {
16 //-----------------------------------------------
17 public struct DataTransform
18 {
19 public float X;
20 public float Y;
21 public float Z;
22 public float RotX;
23 public float RotY;
24 public float RotZ;
25 public float ScaleX;
26 public float ScaleY;
27 public float ScaleZ;
28 }
29 //-----------------------------------------------
30 //Data for enemy
 
Search WWH ::




Custom Search