Unity3D如何读取保存XML,以及用U3D内置方式保存文件
保存工程的信息:比如游戏进程中的位置信息,对抗双方的个人信息等:
方法1:使用xml文件:
xml文件要以UTF-8的格式存储;
但是这样做会使得programmer 可以从脚本中控制xml文件中的所有的字符,包括xml文件中的语法命令字符,因此会带来不安全隐患;
附上两段代码:
A 这一段是我自己写的,将一个xml文件按照字符串读入;
虽然unity3d中的string类型说明中讲到保存的是unicode characters,但是实际上当xml文件比较大的时候,如果保存成unicode,就读不出来,如果保存成UTF-8就不存在这个问题;
using UnityEngine;
using System.Collections;public class ReadXML: MonoBehaviour {
//store the read in file
WWW statusFile;
//decide wether the reading of xml has been finished
bool isReadIn = false;// Use this for initialization
IEnumeratorStart () {//不能用void,否则没有办法使用yield
isReadIn = false;
yield return StartCoroutine(ReadIn());
isReadIn = true;
}
IEnumerator ReadIn()
{
yield return statusFile = new WWW("file:///D:/unity/rotationAndcolor/Assets/information/testxml.xml");//注意路径的写法
}
// Update is called once per frame
void Update () {
if(isReadIn)
{
string statusData = statusFile.data;
print(statusData.Length);
}}
//get the parameters in the xml file
void getPatameters(string _xmlString)
{
//_xmlString.[0]
}
void postParameters()
{
}
}B 这一段代码来自http://www.unifycommunity.com/wiki/index.php?title=Save_and_Load_from_XML
usingUnityEngine;
usingSystem.Collections;
usingSystem.Xml;
usingSystem.Xml.Serialization;
usingSystem.IO;
usingSystem.Text;
publicclass_GameSaveLoad:MonoBehaviour{
// An example where the encoding can be found is at
// http://www.eggheadcafe.com/articles/system.xml.xmlserialization.asp
// We will just use the KISS method and cheat a little and use
// the examples from the web page since they are fully described
// This is our local private members
Rect_Save, _Load, _SaveMSG, _LoadMSG;
bool_ShouldSave, _ShouldLoad,_SwitchSave,_SwitchLoad;
string_FileLocation,_FileName;
publicGameObject_Player;
UserData myData;
string_PlayerName;
string_data;
Vector3VPosition;
// When the EGO is instansiated the Start will trigger
// so we setup our initial values for our local members
voidStart(){
// We setup our rectangles for our messages
_Save=newRect(10,80,100,20);
_Load=newRect(10,100,100,20);
_SaveMSG=newRect(10,120,400,40);
_LoadMSG=newRect(10,140,400,40);
// Where we want to save and load to and from
_FileLocation=Application.dataPath;
_FileName="SaveData.xml";
// for now, lets just set the name to Joe Schmoe
_PlayerName ="Joe Schmoe";
// we need soemthing to store the information into
myData=newUserData();
}
voidUpdate(){}
voidOnGUI()
{
/
stringUTF8ByteArrayToString(byte[]characters)
{
UTF8Encoding encoding =newUTF8Encoding();
stringconstructedString = encoding.GetString(characters);
return(constructedString);
}
byte[]StringToUTF8ByteArray(stringpXmlString)
{
UTF8Encoding encoding =newUTF8Encoding();
byte[]byteArray = encoding.GetBytes(pXmlString);
returnbyteArray;
}
// Here we serialize our UserData object of myData
stringSerializeObject(objectpObject)
{
stringXmlizedString =null;
MemoryStream memoryStream =newMemoryStream();
XmlSerializer xs =newXmlSerializer(typeof(UserData));
XmlTextWriter xmlTextWriter =newXmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, pObject);
memoryStream =(MemoryStream)xmlTextWriter.BaseStream;
XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
returnXmlizedString;
}
// Here we deserialize it back into its original form
objectDeserializeObject(stringpXmlizedString)
{
XmlSerializer xs =newXmlSerializer(typeof(UserData));
MemoryStream memoryStream =newMemoryStream(StringToUTF8ByteArray(pXmlizedString));
XmlTextWriter xmlTextWriter =newXmlTextWriter(memoryStream, Encoding.UTF8);
returnxs.Deserialize(memoryStream);
}
// Finally our save and load methods for the file itself
voidCreateXML()
{
StreamWriter writer;
FileInfo t =newFileInfo(_FileLocation+"//"+ _FileName);
if(!t.Exists)
{
writer = t.CreateText();
}
else
{
t.Delete();
writer = t.CreateText();
}
writer.Write(_data);
writer.Close();
Debug.Log("File written.");
}
voidLoadXML()
{
StreamReader r = File.OpenText(_FileLocation+"//"+ _FileName);
string_info = r.ReadToEnd();
r.Close();
_data=_info;
Debug.Log("File Read");
}
}
// UserData is our custom class that holds our defined objects we want to store in XML format
publicclassUserData
{
// We have to define a default instance of the structure
publicDemoData _iUser;
// Default constructor doesn't really do anything at the moment
publicUserData(){}
// Anything we want to store in the XML file, we define it here
publicstructDemoData
{
publicfloatx;
publicfloaty;
publicfloatz;
publicstringname;
}
}以下是javascript版本
importSystem;
importSystem.Collections;
importSystem.Xml;
importSystem.Xml.Serialization;
importSystem.IO;
importSystem.Text;
// Anything we want to store in the XML file, we define it here
classDemoData
{
varx : float;
vary : float;
varz : float;
varname: String;
}
// UserData is our custom class that holds our defined objects we want to store in XML format
classUserData
{
// We have to define a default instance of the structure
publicvar_iUser : DemoData =newDemoData();
// Default constructor doesn't really do anything at the moment
functionUserData(){}
}
//public class GameSaveLoad: MonoBehaviour {
// An example where the encoding can be found is at
// http://www.eggheadcafe.com/articles/system.xml.xmlserialization.asp
// We will just use the KISS method and cheat a little and use
// the examples from the web page since they are fully described
// This is our local private members
privatevar_Save : Rect;
privatevar_Load : Rect;
privatevar_SaveMSG : Rect;
privatevar_LoadMSG : Rect;
//var _ShouldSave : boolean;
//var _ShouldLoad : boolean;
//var _SwitchSave : boolean;
//var _SwitchLoad : boolean;
privatevar_FileLocation : String;
privatevar_FileName : String ="SaveData.xml";
//public GameObject _Player;
var_Player : GameObject;
var_PlayerName : String ="Joe Schmoe";
privatevarmyData : UserData;
privatevar_data : String;
privatevarVPosition : Vector3;
// When the EGO is instansiated the Start will trigger
// so we setup our initial values for our local members
//function Start () {
functionAwake(){
// We setup our rectangles for our messages
_Save=newRect(10,80,100,20);
_Load=newRect(10,100,100,20);
_SaveMSG=newRect(10,120,200,40);
_LoadMSG=newRect(10,140,200,40);
// Where we want to save and load to and from
_FileLocation=Application.dataPath;
// we need soemthing to store the information into
myData=newUserData();
}
functionUpdate(){}
functionOnGUI()
{
// ***************************************************
// Loading The Player...
// **************************************************
if(GUI.Button(_Load,"Load")){
GUI.Label(_LoadMSG,"Loading from: "+_FileLocation);
// Load our UserData into myData
LoadXML();
if(_data.ToString()!="")
{
// notice how I use a reference to type (UserData) here, you need this
// so that the returned object is converted into the correct type
//myData = (UserData)DeserializeObject(_data);
myData = DeserializeObject(_data);
// set the players position to the data we loaded
VPosition=newVector3(myData._iUser.x,myData._iUser.y,myData._iUser.z);
_Player.transform.position=VPosition;
// just a way to show that we loaded in ok
Debug.Log(myData._iUser.name);
}
}
// ***************************************************
// Saving The Player...
// **************************************************
if(GUI.Button(_Save,"Save")){
GUI.Label(_SaveMSG,"Saving to: "+_FileLocation);
//Debug.Log("SaveLoadXML: sanity check:"+ _Player.transform.position.x);
myData._iUser.x= _Player.transform.position.x;
myData._iUser.y= _Player.transform.position.y;
myData._iUser.z= _Player.transform.position.z;
myData._iUser.name= _PlayerName;
// Time to creat our XML!
_data = SerializeObject(myData);
// This is the final resulting XML from the serialization process
CreateXML();
Debug.Log(_data);
}
}
//string UTF8ByteArrayToString(byte[] characters)
functionUTF8ByteArrayToString(characters : byte[])
{
varencoding : UTF8Encoding =newUTF8Encoding();
varconstructedString : String = encoding.GetString(characters);
return(constructedString);
}
//byte[] StringToUTF8ByteArray(string pXmlString)
functionStringToUTF8ByteArray(pXmlString : String)
{
varencoding : UTF8Encoding =newUTF8Encoding();
varbyteArray : byte[]= encoding.GetBytes(pXmlString);
returnbyteArray;
}
// Here we serialize our UserData object of myData
//string SerializeObject(object pObject)
functionSerializeObject(pObject : Object)
{
varXmlizedString : String =null;
varmemoryStream : MemoryStream =newMemoryStream();
varxs : XmlSerializer =newXmlSerializer(typeof(UserData));
varxmlTextWriter : XmlTextWriter =newXmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, pObject);
memoryStream = xmlTextWriter.BaseStream;// (MemoryStream)
XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
returnXmlizedString;
}
// Here we deserialize it back into its original form
//object DeserializeObject(string pXmlizedString)
functionDeserializeObject(pXmlizedString : String)
{
varxs : XmlSerializer =newXmlSerializer(typeof(UserData));
varmemoryStream : MemoryStream =newMemoryStream(StringToUTF8ByteArray(pXmlizedString));
varxmlTextWriter : XmlTextWriter =newXmlTextWriter(memoryStream, Encoding.UTF8);
returnxs.Deserialize(memoryStream);
}
// Finally our save and load methods for the file itself
functionCreateXML()
{
varwriter : StreamWriter;
//FileInfo t = new FileInfo(_FileLocation+"//"+ _FileName);
vart : FileInfo =newFileInfo(_FileLocation+"/"+ _FileName);
if(!t.Exists)
{
writer = t.CreateText();
}
else
{
t.Delete();
writer = t.CreateText();
}
writer.Write(_data);
writer.Close();
Debug.Log("File written.");
}
functionLoadXML()
{
//StreamReader r = File.OpenText(_FileLocation+"//"+ _FileName);
varr : StreamReader = File.OpenText(_FileLocation+"/"+ _FileName);
var_info : String = r.ReadToEnd();
r.Close();
_data=_info;
Debug.Log("File Read");
}
//}方法2:使用unity 3d 的ISerializable类
它的好处是,可以将文件存成自己定义的后缀形式,并且2进制化存储,在u3d的帮助文档中有相关介绍。
保存工程的信息:比如游戏进程中的位置信息,对抗双方的个人信息等:
方法1:使用xml文件:
xml文件要以UTF-8的格式存储;
但是这样做会使得programmer 可以从脚本中控制xml文件中的所有的字符,包括xml文件中的语法命令字符,因此会带来不安全隐患;
附上两段代码:
A 这一段是我自己写的,将一个xml文件按照字符串读入;
虽然unity3d中的string类型说明中讲到保存的是unicode characters,但是实际上当xml文件比较大的时候,如果保存成unicode,就读不出来,如果保存成UTF-8就不存在这个问题;
using UnityEngine;
using System.Collections;public class ReadXML: MonoBehaviour {
//store the read in file
WWW statusFile;
//decide wether the reading of xml has been finished
bool isReadIn = false;// Use this for initialization
IEnumeratorStart () {//不能用void,否则没有办法使用yield
isReadIn = false;
yield return StartCoroutine(ReadIn());
isReadIn = true;
}
IEnumerator ReadIn()
{
yield return statusFile = new WWW("file:///D:/unity/rotationAndcolor/Assets/information/testxml.xml");//注意路径的写法
}
// Update is called once per frame
void Update () {
if(isReadIn)
{
string statusData = statusFile.data;
print(statusData.Length);
}}
//get the parameters in the xml file
void getPatameters(string _xmlString)
{
//_xmlString.[0]
}
void postParameters()
{
}
}B 这一段代码来自http://www.unifycommunity.com/wiki/index.php?title=Save_and_Load_from_XML
usingUnityEngine;
usingSystem.Collections;
usingSystem.Xml;
usingSystem.Xml.Serialization;
usingSystem.IO;
usingSystem.Text;
publicclass_GameSaveLoad:MonoBehaviour{
// An example where the encoding can be found is at
// http://www.eggheadcafe.com/articles/system.xml.xmlserialization.asp
// We will just use the KISS method and cheat a little and use
// the examples from the web page since they are fully described
// This is our local private members
Rect_Save, _Load, _SaveMSG, _LoadMSG;
bool_ShouldSave, _ShouldLoad,_SwitchSave,_SwitchLoad;
string_FileLocation,_FileName;
publicGameObject_Player;
UserData myData;
string_PlayerName;
string_data;
Vector3VPosition;
// When the EGO is instansiated the Start will trigger
// so we setup our initial values for our local members
voidStart(){
// We setup our rectangles for our messages
_Save=newRect(10,80,100,20);
_Load=newRect(10,100,100,20);
_SaveMSG=newRect(10,120,400,40);
_LoadMSG=newRect(10,140,400,40);
// Where we want to save and load to and from
_FileLocation=Application.dataPath;
_FileName="SaveData.xml";
// for now, lets just set the name to Joe Schmoe
_PlayerName ="Joe Schmoe";
// we need soemthing to store the information into
myData=newUserData();
}
voidUpdate(){}
voidOnGUI()
{
/
stringUTF8ByteArrayToString(byte[]characters)
{
UTF8Encoding encoding =newUTF8Encoding();
stringconstructedString = encoding.GetString(characters);
return(constructedString);
}
byte[]StringToUTF8ByteArray(stringpXmlString)
{
UTF8Encoding encoding =newUTF8Encoding();
byte[]byteArray = encoding.GetBytes(pXmlString);
returnbyteArray;
}
// Here we serialize our UserData object of myData
stringSerializeObject(objectpObject)
{
stringXmlizedString =null;
MemoryStream memoryStream =newMemoryStream();
XmlSerializer xs =newXmlSerializer(typeof(UserData));
XmlTextWriter xmlTextWriter =newXmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, pObject);
memoryStream =(MemoryStream)xmlTextWriter.BaseStream;
XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
returnXmlizedString;
}
// Here we deserialize it back into its original form
objectDeserializeObject(stringpXmlizedString)
{
XmlSerializer xs =newXmlSerializer(typeof(UserData));
MemoryStream memoryStream =newMemoryStream(StringToUTF8ByteArray(pXmlizedString));
XmlTextWriter xmlTextWriter =newXmlTextWriter(memoryStream, Encoding.UTF8);
returnxs.Deserialize(memoryStream);
}
// Finally our save and load methods for the file itself
voidCreateXML()
{
StreamWriter writer;
FileInfo t =newFileInfo(_FileLocation+"//"+ _FileName);
if(!t.Exists)
{
writer = t.CreateText();
}
else
{
t.Delete();
writer = t.CreateText();
}
writer.Write(_data);
writer.Close();
Debug.Log("File written.");
}
voidLoadXML()
{
StreamReader r = File.OpenText(_FileLocation+"//"+ _FileName);
string_info = r.ReadToEnd();
r.Close();
_data=_info;
Debug.Log("File Read");
}
}
// UserData is our custom class that holds our defined objects we want to store in XML format
publicclassUserData
{
// We have to define a default instance of the structure
publicDemoData _iUser;
// Default constructor doesn't really do anything at the moment
publicUserData(){}
// Anything we want to store in the XML file, we define it here
publicstructDemoData
{
publicfloatx;
publicfloaty;
publicfloatz;
publicstringname;
}
}以下是javascript版本
importSystem;
importSystem.Collections;
importSystem.Xml;
importSystem.Xml.Serialization;
importSystem.IO;
importSystem.Text;
// Anything we want to store in the XML file, we define it here
classDemoData
{
varx : float;
vary : float;
varz : float;
varname: String;
}
// UserData is our custom class that holds our defined objects we want to store in XML format
classUserData
{
// We have to define a default instance of the structure
publicvar_iUser : DemoData =newDemoData();
// Default constructor doesn't really do anything at the moment
functionUserData(){}
}
//public class GameSaveLoad: MonoBehaviour {
// An example where the encoding can be found is at
// http://www.eggheadcafe.com/articles/system.xml.xmlserialization.asp
// We will just use the KISS method and cheat a little and use
// the examples from the web page since they are fully described
// This is our local private members
privatevar_Save : Rect;
privatevar_Load : Rect;
privatevar_SaveMSG : Rect;
privatevar_LoadMSG : Rect;
//var _ShouldSave : boolean;
//var _ShouldLoad : boolean;
//var _SwitchSave : boolean;
//var _SwitchLoad : boolean;
privatevar_FileLocation : String;
privatevar_FileName : String ="SaveData.xml";
//public GameObject _Player;
var_Player : GameObject;
var_PlayerName : String ="Joe Schmoe";
privatevarmyData : UserData;
privatevar_data : String;
privatevarVPosition : Vector3;
// When the EGO is instansiated the Start will trigger
// so we setup our initial values for our local members
//function Start () {
functionAwake(){
// We setup our rectangles for our messages
_Save=newRect(10,80,100,20);
_Load=newRect(10,100,100,20);
_SaveMSG=newRect(10,120,200,40);
_LoadMSG=newRect(10,140,200,40);
// Where we want to save and load to and from
_FileLocation=Application.dataPath;
// we need soemthing to store the information into
myData=newUserData();
}
functionUpdate(){}
functionOnGUI()
{
// ***************************************************
// Loading The Player...
// **************************************************
if(GUI.Button(_Load,"Load")){
GUI.Label(_LoadMSG,"Loading from: "+_FileLocation);
// Load our UserData into myData
LoadXML();
if(_data.ToString()!="")
{
// notice how I use a reference to type (UserData) here, you need this
// so that the returned object is converted into the correct type
//myData = (UserData)DeserializeObject(_data);
myData = DeserializeObject(_data);
// set the players position to the data we loaded
VPosition=newVector3(myData._iUser.x,myData._iUser.y,myData._iUser.z);
_Player.transform.position=VPosition;
// just a way to show that we loaded in ok
Debug.Log(myData._iUser.name);
}
}
// ***************************************************
// Saving The Player...
// **************************************************
if(GUI.Button(_Save,"Save")){
GUI.Label(_SaveMSG,"Saving to: "+_FileLocation);
//Debug.Log("SaveLoadXML: sanity check:"+ _Player.transform.position.x);
myData._iUser.x= _Player.transform.position.x;
myData._iUser.y= _Player.transform.position.y;
myData._iUser.z= _Player.transform.position.z;
myData._iUser.name= _PlayerName;
// Time to creat our XML!
_data = SerializeObject(myData);
// This is the final resulting XML from the serialization process
CreateXML();
Debug.Log(_data);
}
}
//string UTF8ByteArrayToString(byte[] characters)
functionUTF8ByteArrayToString(characters : byte[])
{
varencoding : UTF8Encoding =newUTF8Encoding();
varconstructedString : String = encoding.GetString(characters);
return(constructedString);
}
//byte[] StringToUTF8ByteArray(string pXmlString)
functionStringToUTF8ByteArray(pXmlString : String)
{
varencoding : UTF8Encoding =newUTF8Encoding();
varbyteArray : byte[]= encoding.GetBytes(pXmlString);
returnbyteArray;
}
// Here we serialize our UserData object of myData
//string SerializeObject(object pObject)
functionSerializeObject(pObject : Object)
{
varXmlizedString : String =null;
varmemoryStream : MemoryStream =newMemoryStream();
varxs : XmlSerializer =newXmlSerializer(typeof(UserData));
varxmlTextWriter : XmlTextWriter =newXmlTextWriter(memoryStream, Encoding.UTF8);
xs.Serialize(xmlTextWriter, pObject);
memoryStream = xmlTextWriter.BaseStream;// (MemoryStream)
XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
returnXmlizedString;
}
// Here we deserialize it back into its original form
//object DeserializeObject(string pXmlizedString)
functionDeserializeObject(pXmlizedString : String)
{
varxs : XmlSerializer =newXmlSerializer(typeof(UserData));
varmemoryStream : MemoryStream =newMemoryStream(StringToUTF8ByteArray(pXmlizedString));
varxmlTextWriter : XmlTextWriter =newXmlTextWriter(memoryStream, Encoding.UTF8);
returnxs.Deserialize(memoryStream);
}
// Finally our save and load methods for the file itself
functionCreateXML()
{
varwriter : StreamWriter;
//FileInfo t = new FileInfo(_FileLocation+"//"+ _FileName);
vart : FileInfo =newFileInfo(_FileLocation+"/"+ _FileName);
if(!t.Exists)
{
writer = t.CreateText();
}
else
{
t.Delete();
writer = t.CreateText();
}
writer.Write(_data);
writer.Close();
Debug.Log("File written.");
}
functionLoadXML()
{
//StreamReader r = File.OpenText(_FileLocation+"//"+ _FileName);
varr : StreamReader = File.OpenText(_FileLocation+"/"+ _FileName);
var_info : String = r.ReadToEnd();
r.Close();
_data=_info;
Debug.Log("File Read");
}
//}
方法2:使用unity 3d 的ISerializable类
它的好处是,可以将文件存成自己定义的后缀形式,并且2进制化存储,在u3d的帮助文档中有相关介绍。