Unity3D如何读取保存XML,以及用U3D内置方式保存文件

前端之家收集整理的这篇文章主要介绍了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;
usingXml;
usingXml.Serialization;
usingIO;
usingText;

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,0)">100,0)">20);
_Load=);
_SaveMSG=120,0)">400,0)">40);
_LoadMSG=140,0)">);

// 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)
/
stringUTF8ByteArrayToStringbyte[]characters{
UTF8Encoding encoding =newUTF8Encoding);
stringconstructedString = encoding.GetString(characters);
return(constructedString}

]StringToUTF8ByteArraystringpXmlString]byteArray = encoding.GetBytes(pXmlStringreturnbyteArray;
}

// Here we serialize our UserData object of myData
stringSerializeObjectobjectpObject{
stringXmlizedString =null;
MemoryStream memoryStream =newMemoryStream);
XmlSerializer xs =newXmlSerializertypeof(UserData);
XmlTextWriter xmlTextWriter =newXmlTextWriter(memoryStream,Encoding.UTF8);
xs.Serialize(xmlTextWriter,pObject);
memoryStream =(MemoryStream)xmlTextWriter.BaseStream;
XmlizedString = UTF8ByteArrayToString(memoryStream.ToArrayreturnXmlizedString;
// Here we deserialize it back into its original form
objectDeserializeObjectstringpXmlizedString{
XmlSerializer xs =);
MemoryStream memoryStream =(StringToUTF8ByteArray(pXmlizedStringreturnxs.Deserialize(memoryStream// Finally our save and load methods for the file itself
voidCreateXML{
StreamWriter writer;
FileInfo t =newFileInfo(_FileLocation+"//"+ _FileNameif(!t.Exists{
writer = t.CreateText}
else
{
t.Delete);
writer = t.}
writer.Write(_data);
writer.Close);
Debug.Log("File written."voidLoadXML{
StreamReader r = File.OpenTextstring_info = r.ReadToEnd);
r.);
_data=_info;
"File Read"}
// 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
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
structDemoData
{
floatx;
floaty;
floatz;
stringname;
}

以下是javascript版本

importSystem;
System.Collections;
Xml.SerializationIOText;

// Anything we want to store in the XML file,we define it here
classDemoData
{
varx : float;
y : float;
z : float;
name: String;
}

// UserData is our custom class that holds our defined objects we want to store in XML format
UserData
// We have to define a default instance of the structure
public_iUser : DemoData =newDemoData()// Default constructor doesn't really do anything at the moment
functionUserData){}
//public class GameSaveLoad: MonoBehav
IoUr {

// 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
private_Save : Rect;
_Load : Rect;
_SaveMSG : Rect;
_LoadMSG : Rect;
//var _ShouldSave : boolean;
//var _ShouldLoad : boolean;
//var _SwitchSave : boolean;
//var _SwitchLoad : boolean;
_FileLocation : String;
_FileName : String ="SaveData.xml"//public GameObject _Player;
_Player : GameObject;
_PlayerName : String ="Joe Schmoe"myData : UserData;
_data : String;

VPosition : Vector3;

// When the EGO is instansiated the Start will trigger
// so we setup our initial values for our local members
//function Start () {
Awake{
// We setup our rectangles for our messages
_Save=Rect(10,8010020;
_Load=
;
_SaveMSG=
12020040;
_LoadMSG=
140// Where we want to save and load to and from
_FileLocation=Application.dataPath;


// we need soemthing to store the information into
myData=;
}
UpdateOnGUI)


// ***************************************************
// Loading The Player...
// **************************************************
if(GUI.Button_Load,"Load"
GUI.
Label_LoadMSG,204)">"Loading from: "+_FileLocation// Load our UserData into myData
LoadXML_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=Vector3myData._iUser.xyz;
_Player.
transformposition=VPosition;
// just a way to show that we loaded in ok
Debug.Logname
// Saving The Player...
_Save,204)">"Save"_SaveMSG,204)">"Saving to: "//Debug.Log("SaveLoadXML: sanity check:"+ _Player.transform.position.x);

myData._iUser.
= _Player.;
myData._iUser.
z= _PlayerName;

// Time to creat our XML!
_data = SerializeObjectmyData// This is the final resulting XML from the serialization process
CreateXML;
Debug.
}




//string UTF8ByteArrayToString(byte[] characters)
UTF8ByteArrayToStringcharacters : byte[]encoding : UTF8Encoding =UTF8EncodingconstructedString : String = encoding.GetStringcharactersreturnconstructedString//byte[] StringToUTF8ByteArray(string pXmlString)
StringToUTF8ByteArraypXmlString : StringbyteArray : byte]= encoding.GetBytespXmlStringreturnbyteArray;
// Here we serialize our UserData object of myData
//string SerializeObject(object pObject)
SerializeObjectpObject : ObjectXmlizedString : String =nullmemoryStream : MemoryStream =MemoryStreamxs : XmlSerializer =XmlSerializertypeofxmlTextWriter : XmlTextWriter =XmlTextWritermemoryStream,Encoding.UTF8;
xs.
SerializexmlTextWriter,pObject;
memoryStream = xmlTextWriter.
BaseStream;// (MemoryStream)
XmlizedString = UTF8ByteArrayToStringmemoryStream.ToArrayXmlizedString;
// Here we deserialize it back into its original form
//object DeserializeObject(string pXmlizedString)
DeserializeObjectpXmlizedString : StringpXmlizedStringxs.DeserializememoryStream// Finally our save and load methods for the file itself
writer : StreamWriter;
//FileInfo t = new FileInfo(_FileLocation+"//"+ _FileName);
t : FileInfo =FileInfo_FileLocation+"/"+ _FileName!t.Existswriter = t.CreateTextelse
t.Delete;
writer = t.
writer.Write;
writer.
Close("File written."//StreamReader r = File.OpenText(_FileLocation+"//"+ _FileName);
r : StreamReader = File.OpenText_info : String = r.ReadToEnd;
r.
;
_data=_info;
Debug.
"File Read"//}

方法2:使用unity 3d 的ISerializable类

它的好处是,可以将文件存成自己定义的后缀形式,并且2进制化存储,在u3d的帮助文档中有相关介绍。

猜你在找的XML相关文章