Unity3d IO流3)之XML研究

节主要写的东西是XML。

首先我们要理解一下序列化的概念:序列化是将对象状态转换为可保持或传输的格式的过程。与序列化相对的是反序列化,它将流转换为对象。这两个过程结合起来,可以轻松地存储和传输数据。

要了解详细点就参考百科:http://baike.baidu.com/view/160029.htm

这些东西有点抽象。我和大家分享一下我个人对序列化的理解,大牛们多多赐教^-^

比如:我们有一个类A,

class A{

public int age;

public string name;

};

我们把A序列化为XML,以方便对数据的解析。

<A>

<age>value</age>

<name>value</name>

</A>

很形象吧,呵呵。反序列化就是把下面的序列化成上面的啦

好了,我们步入正题。

我们需要写2个工具类,这个2个类不需要赋给任何物体。

原始代码:请参看官方的http://wiki.unity3d.com/index.php?title=Save_and_Load_from_XML; 我这里做了些修改。方便我们大家更好的使用XML对数据的读写操作。

你要保存数据,就save一下,调用方法是PlayerData.SaveFile(),读取数据就load一下,调用方法是PlayerData.LoadFile();

工具类之一:PlayerData类

//author :by taotao
//date:2012/12/24
//purpose:为了共享,一起学习,一起交流,一起进步
using UnityEngine;
using System.Collections;
using System;//for Exception
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Text;
#if UNITY_EDITOR
using UnityEditor;
#endif


public class PlayerData
{
//xml的保存路径
public static string xmlPath = Application.dataPath + "/XMLFile/XMLData/Files.xml";
//玩家的游戏数据
public static GameData gameData;

public static bool SaveFile()
{
try
{
if(gameData==null)
throw new Exception("gameData is null");
CreateXML(SerializeObject(gameData));
}
catch(Exception e)
{
Debug.LogError(e.Message);
return false;
}
return true;

}

public static bool LoadFile()
{
try
{
string data=LoadXML();
gameData=(GameData)DeserializeObject(data);
}
catch(Exception e)
{
Debug.LogError(e.Message);
return false;
}
return true;
}

protected static void CreateXML(string data)
{
StreamWriter writer;
FileInfo file=new FileInfo(xmlPath);
if(file.Exists)
file.Delete();
writer=file.CreateText();
writer.Write(data);
writer.Close();
Debug.Log("File Written");
//更新一下
#if UNITY_EDITOR
AssetDatabase.Refresh();
#endif

}

protected static string LoadXML()
{
if(!File.Exists(xmlPath))
throw new Exception("File not exist or no access:"+xmlPath);
StreamReader reader=File.OpenText(xmlPath);
string data=reader.ReadToEnd();
reader.Close();
if(data==null|| data.Length<1)
throw new Exception("read error:data"+((data==null)?" null":" length=0"));
Debug.Log("File Read");
return data;
}

protected static string UTF8ByteArrayToString(byte[] characters)
{
UTF8Encoding encoding=new UTF8Encoding();
string constructedString=encoding.GetString(characters);
return constructedString;
}

protected static byte[] StringToUTF8ByteArray(string xmlString)
{
UTF8Encoding encoding=new UTF8Encoding();
byte[] byteArray=encoding.GetBytes(xmlString);
return byteArray;
}

protected static string SerializeObject(object pObject)
{
string xmlizedString=null;
MemoryStream memoryStream=new MemoryStream();
XmlSerializer xs=new XmlSerializer(typeof(GameData));
XmlTextWriter xmlTextWriter=new XmlTextWriter(memoryStream,Encoding.UTF8);
xs.Serialize(xmlTextWriter,pObject);
memoryStream=(MemoryStream)xmlTextWriter.BaseStream;
xmlizedString=UTF8ByteArrayToString(memoryStream.ToArray());
return xmlizedString;
}

protected static object DeserializeObject(string xmlizedString)
{
XmlSerializer xs=new XmlSerializer(typeof(GameData));
MemoryStream memoryStream=new MemoryStream(StringToUTF8ByteArray(xmlizedString));
return xs.Deserialize(memoryStream);
}
}

工具类之二:PlayerInfo

这个类是你的游戏里需要保存,读写的数据。

这里只是简单的写了一点点:具体数据要玩家写

using UnityEngine;
using System.Collections;
using System.Collections.Generic;//List要用到这个命名空间
using System;//string要用到这个命名空间
//需要加上这个在类上,好序列化对象
[System.Serializable]
public class GameData
{
public string m_gameName;
public List<PlayerInfo> m_playerInfo;
public GameData()
{
m_gameName=null;
m_playerInfo=new List<PlayerInfo>();
}
public GameData(string gameName)
{
m_gameName=gameName;
m_playerInfo=new List<PlayerInfo>();
}
}
//需要加上这个在类上,好序列化对象
[System.Serializable]
public class PlayerInfo{

public string m_playerName;
public int[] m_hp;
public List<int> m_mp;
public PlayerInfo()
{
m_playerName=null;
m_hp=new int[0];
m_mp=new List<int>();
}
public PlayerInfo(string playerName)
{
m_playerName=playerName;
m_hp=new int[0];
m_mp=new List<int>();
}
}
好了,u3d里xml的读写操作就写完了。呵呵,为了告诉大家如何使用。还需要一步:

我们在u3d里的GUI打印出来,方便大家更好的理解:

这里我们需要写个脚本。我暂且命名:UserDemo

具体脚本如下:

using UnityEngine;
using System.Collections;

public class UserDemo : MonoBehaviour {

private GameData gameData;
private PlayerInfo demoInfo;

void Start()
{
//我们把游戏的初始化为:DemoGame,这个你可以任意命名啦
gameData=new GameData("DemoGame");
demoInfo=new PlayerInfo("subItem1:");
demoInfo.m_hp=new int[5];
for(int i=0;i<demoInfo.m_hp.Length;i++)
demoInfo.m_hp[i]=2*i+1;
for(int i=0;i<5;i++)
demoInfo.m_mp.Add(3*i+2);
gameData.m_playerInfo.Add(demoInfo);

demoInfo=new PlayerInfo("subItem2:");
demoInfo.m_hp=new int[8];
for(int i=0;i<demoInfo.m_hp.Length;i++)
demoInfo.m_hp[i]=Random.Range(1,4)+2*i;
for(int i=0;i<8;i++)
demoInfo.m_mp.Add(Random.Range(3,10)+3*i);
gameData.m_playerInfo.Add(demoInfo);

PlayerData.gameData=gameData;
}

void OnGUI()
{
GUILayout.BeginArea(new Rect(0,Screen.width,Screen.height));
GUILayout.BeginHorizontal();
GUILayout.FlexibleSpace();
GUILayout.BeginVertical();
GUILayout.FlexibleSpace();

if(GUILayout.Button("Clear:"))
{
PlayerData.gameData=null;
}
if(GUILayout.Button("Save:"))
{
bool isSave=PlayerData.SaveFile();
Debug.Log("save:"+isSave);
}
if(GUILayout.Button("Load:"))
{
bool isLoad=PlayerData.LoadFile();
Debug.Log("load:"+isLoad);
}
GUILayout.Space(20);
if(PlayerData.gameData!=null)
{
GameData data=PlayerData.gameData;
GUILayout.Label(data.m_gameName+" have :"+data.m_playerInfo.Count.ToString()+" subItem");
for(int i=0;i<data.m_playerInfo.Count;i++)
{
GUILayout.Label(data.m_playerInfo[i].m_playerName+" hp:"+data.m_playerInfo[i].m_hp.Length
+" mp:"+data.m_playerInfo[i].m_mp.Count);
string hp="";
for(int j=0;j<data.m_playerInfo[i].m_hp.Length;j++)
{
hp+=data.m_playerInfo[i].m_hp[j].ToString()+" ";
}
GUILayout.Label(hp);
string mp="";
for(int k=0;k<data.m_playerInfo[i].m_mp.Count;k++)
{
mp+=data.m_playerInfo[i].m_mp[k].ToString()+" ";
}
GUILayout.Label(mp);
}
}

GUILayout.FlexibleSpace();
GUILayout.EndVertical();
GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.EndArea();

}
}

好了,我们运行一下u3d

Unity3d<wbr>IO流(3)之XML研究


我们便会看到,蓝色区域里的数据了,这些数据使我们写入的数据

Unity3d<wbr>IO流(3)之XML研究


之后我们保存一下

Unity3d<wbr>IO流(3)之XML研究


在工程面板里便会多出来File.xml文件了;在检测面板里你便能看到我们写的数据了

Unity3d<wbr>IO流(3)之XML研究

为了方便我们大家的阅读,我们定位到Files文件夹里,用IE打开,如下

Unity3d<wbr>IO流(3)之XML研究


以上的数据多清晰啊。^-^.我们点击clear按钮

Unity3d<wbr>IO流(3)之XML研究


数据便清干净了。

Unity3d<wbr>IO流(3)之XML研究


接着,我们点击一下load按钮

Unity3d<wbr>IO流(3)之XML研究


数据又加载进来了。

Unity3d<wbr>IO流(3)之XML研究



这里我们没有对数据进行加密处理,其实加密也不难。我们在PlayerData工具类里加入2个方法就OK了,一个字符串key。

不要忘了加入using System.Security.Cryptography;这个命名空间

public static string encryptKey = "dtao1357";

/// 字符串加密
private static string Encrypt(string str)
{

//实例化加密解密对象

DESCryptoServiceProvider desc = new DESCryptoServiceProvider();

//定义字节数组、用来存储密钥
byte[] key = UTF8Encoding.UTF8.GetBytes(encryptKey);

//定义字节数组、用来存储要解密的字符串
byte[] data = UTF8Encoding.UTF8.GetBytes(str);

//实例化内存流对象
MemoryStream ms = new MemoryStream();

//使用内存流实例化加密流对象
CryptoStream cstream = new CryptoStream(ms,desc.CreateEncryptor(key,key),
CryptoStreamMode.Write);

//向加密流中写入数据
cstream.Write(data,data.Length);

//释放加密流
cstream.FlushFinalBlock();

//返回加密后的字符串
return Convert.ToBase64String(ms.ToArray());
}

//解密字符串
private static string Decrypt(string str)
{
DESCryptoServiceProvider desc = new DESCryptoServiceProvider();
byte[] key = UTF8Encoding.UTF8.GetBytes(encryptKey);
byte[] data = Convert.FromBase64String(str);
MemoryStream mstream = new MemoryStream();
CryptoStream cstream = new CryptoStream(mstream,desc.CreateDecryptor
(key,CryptoStreamMode.Write);
cstream.Write(data,data.Length);
cstream.FlushFinalBlock();
return UTF8Encoding.UTF8.GetString(mstream.ToArray());
}

Unity3d<wbr>IO流(3)之XML研究

相应的CreateXML和LoadXML也要修改一下

protected static void CreateXML(string data)
{
StreamWriter writer;
FileInfo file=new FileInfo(xmlPath);
if(file.Exists)
file.Delete();
writer=file.CreateText();
//writer.Write(data);//把这里注视掉
//换成如下*************/
string xx = Encrypt(data);//加密
writer.Write(xx);
writer.Close();
Debug.Log("File Written");
//更新一下
#if UNITY_EDITOR
AssetDatabase.Refresh();
#endif

}

protected static string LoadXML()
{
if(!File.Exists(xmlPath))
throw new Exception("File not exist or no access:"+xmlPath);
StreamReader reader=File.OpenText(xmlPath);
string data=reader.ReadToEnd();
reader.Close();
if(data==null|| data.Length<1)
throw new Exception("read error:data"+((data==null)?" null":" length=0"));
Debug.Log("File Read");
//return data;//注视掉
//换成如下**********************/
string xx = Decrypt(data);//解密
return xx;

}

Unity3d<wbr>IO流(3)之XML研究

好了这些弄完之后,我们运行一下u3d并点击save按钮一下:

Unity3d<wbr>IO流(3)之XML研究


我们便能在监视面板里看到一大堆加密字符串了

Unity3d<wbr>IO流(3)之XML研究


为了方便我们大家查看,我也也用ie打开一下,结果如下:究其原因,应该使我们对数据加密了,所以才会这个的

Unity3d<wbr>IO流(3)之XML研究

我们点击一下clear按钮,清除一下数据

Unity3d<wbr>IO流(3)之XML研究


游戏面板变成如下,我们点击一下load按钮,看看我们的数据解密没有

Unity3d<wbr>IO流(3)之XML研究


解密了,因为我们看到的不是乱码。哇咔咔(*^__^*)

Unity3d<wbr>IO流(3)之XML研究


好了,我们对xml的编写完了。不早了,晚安啦!

下次教程我会写一个小游戏,用到我这节写的2个工具类脚本。好更能加深大家的印象。

转载:http://blog.sina.com.cn/s/blog_a4c1823d0101czfd.html

相关文章

这篇文章将为大家详细讲解有关Unity3D中如何通过Animator动画...
这篇文章主要介绍了Unity3D如何播放游戏视频,具有一定借鉴价...
这篇文章给大家分享的是有关Unity3D各平台路径是什么的内容。...
小编给大家分享一下Unity3D如何实现移动平台上的角色阴影,希...
如何解析基于Unity3D的平坦四叉树地形与Virtual Texture的分...
这篇文章主要介绍Unity3D如何实现动态分辨率降低渲染开销,文...