前端之家收集整理的这篇文章主要介绍了
unity序列化和反序列XML,并添加属性,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
- usingUnityEngine;
- usingSystem.Collections;
- usingSystem.Xml;
- usingSystem.Xml.Serialization;
- usingSystem.IO;
- usingSystem.Text;
-
- publicclassReward
- {
- publicTasktask;
- publicAttributeattribute;
- publicReward(){}
- publicstructTask
- {
- [XmlAttribute("taskNo")]
- publicinttaskNo{get;set;}
- [XmlAttribute("taskReward")]
- publicinttaskReward{get;set;}
- publicIdid1;
- publicIdid2;
- publicIdid3;
- }
- publicstructId
- [XmlAttribute("flag")]
- publicboolflag{get;set;}
- [XmlAttribute("name")]
- publicstringname{get;set;}
- }
- publicclassAchievementManager:MonoBehavIoUr{
- Rewardreward;
- FileInfot;
- string_data;
- voidStart()
- reward=newReward();
- t=newFileInfo(Application.dataPath+"\\"+"Achievement.xml");
- LoadXML();
- reward.task.id1.name="杨纯/nate";
- reward.task.id2.name="有点笨";
- reward.task.id3.name="dlnuchunge";
- Save();
-
- voidLoadXML()
- if(t.Exists)
- StreamReaderr=t.OpenText();
- string_info=r.ReadToEnd();
- r.Close();
- _data=_info;
- if(_data.ToString()!="")
- reward=(Reward)DeserializeObject(_data);
- publicvoidSave()
- _data=SerializeObject(reward);
- StreamWriterwriter;
- t.Delete();
- writer=t.CreateText();
- writer.Write(_data);
- writer.Close();
- stringUTF8ByteArrayToString(byte[]characters)
- UTF8Encodingencoding=newUTF8Encoding();
- stringconstructedString=encoding.GetString(characters);
- return(constructedString);
- byte[]StringToUTF8ByteArray(stringpXmlString)
- UTF8Encodingencoding=newUTF8Encoding();
- byte[]byteArray=encoding.GetBytes(pXmlString);
- returnbyteArray;
- //HereweserializeourRewardobjectofreward
- stringSerializeObject(objectpObject)
- stringXmlizedString=null;
- MemoryStreammemoryStream=newMemoryStream();
- XmlSerializerxs=newXmlSerializer(typeof(Reward));
- XmlTextWriterxmlTextWriter=newXmlTextWriter(memoryStream,Encoding.UTF8);
- xs.Serialize(xmlTextWriter,pObject);
- memoryStream=(MemoryStream)xmlTextWriter.BaseStream;
- XmlizedString=UTF8ByteArrayToString(memoryStream.ToArray());
- returnXmlizedString;
- //Herewedeserializeitbackintoitsoriginalform
- objectDeserializeObject(stringpXmlizedString)
- XmlSerializerxs=newXmlSerializer(typeof(Reward));
- MemoryStreammemoryStream=newMemoryStream(StringToUTF8ByteArray(pXmlizedString));
- returnxs.Deserialize(memoryStream);
- }
原文链接:https://www.f2er.com/xml/298804.html