您好,欢迎访问三七文档
当前位置:首页 > 电子/通信 > 综合/其它 > XML学习保存和读取
///summary///菩提本无树///明镜亦非台///本来无一物///何处染尘埃////summaryusingUnityEngine;usingSystem.Collections;usingSystem.Xml;usingSystem.Xml.Serialization;usingSystem.IO;usingSystem.Text;usingSystem.Collections.Generic;publicclass_GameSaveLoad:MonoBehaviour{//Anexamplewheretheencodingcanbefoundisat//[url=][/url]//WewilljustusetheKISSmethodandcheatalittleanduse//theexamplesfromthewebpagesincetheyarefullydescribed//ThisisourlocalprivatemembersRect_Save,_Load,_SaveMSG,_LoadMSG;bool_ShouldSave,_ShouldLoad,_SwitchSave,_SwitchLoad;string_FileLocation,_FileName;privateGameObject[]_Player;//存储克隆物体ListUserDatamyData;string_data;publicGameObjectcube;//用于克隆的gameobjectVector3VPosition;//记录物体的坐标privatebool_isOver=false;//用于标记是否克隆privateintobjname=0;//用于记录克隆物体的个数及赋给该克隆体的名字//WhentheEGOisinstansiatedtheStartwilltrigger//sowesetupourinitialvaluesforourlocalmembersvoidStart(){_Player=newGameObject[100];//Wesetupourrectanglesforourmessages_Save=newRect(10,80,100,20);_Load=newRect(10,100,100,20);_SaveMSG=newRect(10,120,400,40);_LoadMSG=newRect(10,140,400,40);//Wherewewanttosaveandloadtoandfrom_FileLocation=Application.dataPath;_FileName=SaveData.xml;//fornow,letsjustsetthenametoJoeSchmoemyData=newListUserData();//weneedsoemthingtostoretheinformationinto}voidUpdate(){//用于克隆物体,克隆物体的坐标(x,y)为鼠标左键点击位置,z为被克隆物体的zif(_isOver){if(Input.GetMouseButtonDown(0)){Vector3MousePosition=Camera.main.ScreenToWorldPoint(Input.mousePosition);GameObjectobj=Instantiate(cube,newVector3(MousePosition.x,MousePosition.y,cube.transform.position.z),Quaternion.identity)asGameObject;_Player[objname]=obj;obj.name=+objname;objname++;}}}//开始克隆功能函数publicvoidbeginClone(){_isOver=true;}//结束克隆功能函数及鼠标放在按钮上停止克隆publicvoidendClone(){_isOver=false;}voidOnGUI(){//***************************************************//LoadingThePlayer...//**************************************************if(GUI.Button(_Load,Load)){GUI.Label(_LoadMSG,Loadingfrom:+_FileLocation);//LoadourUserDataintomyDataLoadXML();if(_data.ToString()!=){//noticehowIuseareferencetotype(UserData)here,youneedthis//sothatthereturnedobjectisconvertedintothecorrecttypemyData=(ListUserData)DeserializeObject(_data);Debug.Log(myData.Count);//settheplayerspositiontothedataweloadedfor(inti=0;imyData.Count;i++){UserDataOneData=myData[i];VPosition=newVector3(OneData._iUser.x,OneData._iUser.y,OneData._iUser.z);GameObjectReObj=Instantiate(cube,VPosition,Quaternion.identity)asGameObject;ReObj.name=OneData._iUser.name;Debug.Log(OneData._iUser.name);}//justawaytoshowthatweloadedinok}}//***************************************************//SavingThePlayer...//**************************************************if(GUI.Button(_Save,Save)){GUI.Label(_SaveMSG,Savingto:+_FileLocation);for(inti=0;iobjname;i++){UserDataOneData=newUserData();OneData._iUser.x=_Player[i].transform.position.x;OneData._iUser.y=_Player[i].transform.position.y;OneData._iUser.z=_Player[i].transform.position.z;OneData._iUser.name=_Player[i].name;myData.Add(OneData);}//TimetocreatourXML!_data=SerializeObject(myData);//ThisisthefinalresultingXMLfromtheserializationprocessCreateXML();Debug.Log(_data);}}//将二进制数据流转化为字符串stringUTF8ByteArrayToString(byte[]characters){UTF8Encodingencoding=newUTF8Encoding();stringconstructedString=encoding.GetString(characters);return(constructedString);}//将字符串转化为二进制数据流byte[]StringToUTF8ByteArray(stringpXmlString){byte[]byteArray=Encoding.UTF8.GetBytes(pXmlString);returnbyteArray;}//HereweserializeourUserDataobjectofmyData序列化数据stringSerializeObject(objectpObject){stringXmlizedString=null;MemoryStreammemoryStream=newMemoryStream();XmlSerializerxs=newXmlSerializer(typeof(ListUserData));XmlTextWriterxmlTextWriter=newXmlTextWriter(memoryStream,Encoding.UTF8);xs.Serialize(xmlTextWriter,pObject);memoryStream=(MemoryStream)xmlTextWriter.BaseStream;XmlizedString=UTF8ByteArrayToString(memoryStream.ToArray());returnXmlizedString;}//Herewedeserializeitbackintoitsoriginalform反序列化数据objectDeserializeObject(stringpXmlizedString){XmlSerializerxs=newXmlSerializer(typeof(ListUserData));MemoryStreammemoryStream=newMemoryStream(StringToUTF8ByteArray(pXmlizedString));XmlTextWriterxmlTextWriter=newXmlTextWriter(memoryStream,Encoding.UTF8);returnxs.Deserialize(memoryStream);}//Finallyoursaveandloadmethodsforthefileitself创建XML文件voidCreateXML(){StreamWriterwriter;FileInfot=newFileInfo(_FileLocation+\\+_FileName);if(!t.Exists){writer=t.CreateText();}else{t.Delete();writer=t.CreateText();}writer.Write(_data);writer.Close();Debug.Log(Filewritten.);}//读取XML文件voidLoadXML(){StreamReaderr=File.OpenText(_FileLocation+\\+_FileName);string_info=r.ReadToEnd();r.Close();_data=_info;Debug.Log(FileRead);Debug.Log(_data);}}//UserDataisourcustomclassthatholdsourdefinedobjectswewanttostoreinXMLformat//用于存储场景内物体的信息(坐标和名字)publicclassUserData{//WehavetodefineadefaultinstanceofthestructurepublicDemoData_iUser;//Defaultconstructordoesn'treallydoanythingatthemomentp
本文标题:XML学习保存和读取
链接地址:https://www.777doc.com/doc-2868156 .html