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: 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
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的帮助文档中有相关介绍。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


这篇文章将为大家详细讲解有关Unity3D中如何通过Animator动画状态机获取任意animation clip的准确播放持续时长,小编觉得挺实用的,因此分享给大家做个参考,
这篇文章主要介绍了Unity3D如何播放游戏视频,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解
这篇文章给大家分享的是有关Unity3D各平台路径是什么的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。1、Resources路径 Reso...
小编给大家分享一下Unity3D如何实现移动平台上的角色阴影,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!由于目前主流使用Unity3.x在移动平...
如何解析基于Unity3D的平坦四叉树地形与Virtual Texture的分析,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希
这篇文章主要介绍Unity3D如何实现动态分辨率降低渲染开销,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!之前项目降低分辨率我们都普...
这篇文章主要介绍了unity3d中如何使用屏幕空间改善shadowmap漏光,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编...
这篇文章主要介绍unity3d如何实现基于屏幕空间的描边,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!Outline(Based on Image Space)由...
这篇文章给大家分享的是有关unity3d中导入fbx时的Scale是什么的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。在Unity中点击GameOb...
这篇文章主要为大家展示了“unity3d中如何实现ttc转ttf及制作字体”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习
这篇文章主要介绍了unity3d中水彩风渲染有什么用,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了...
这篇文章将为大家详细讲解有关unity3d中图像压缩原理是什么,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。1 图像可压缩...
这篇文章给大家分享的是有关unity3d中光照公式有哪些的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。漫反射、高光、物理渲染(PBR...
小编给大家分享一下unity3d中光照探针的示例分析,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我...
这篇文章将为大家详细讲解有关Unity3D中Rendering Paths及LightMode的示例分析,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有
这篇文章将为大家详细讲解有关unity3d中图形学的光照原理是什么,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。首先,在...
这篇文章给大家分享的是有关unity3d中图片渲染流程是什么的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。相关名词GPU(Graphic Pr...
本篇我们来介绍一下左侧工具栏中基本绘制的应用。 一、墙体绘制直墙 & 矩形墙绘制墙体时,可以看到上方的工具栏中对墙体进行参数的设定。 弧形墙在建筑版的户...
xlua是由腾讯维护的一个开源项目,我们可以在github上下载这个开源项目并查看一些相关文档官网:https://github.com/Tencent/xLua配置文档:https://github.com/Tencent/xLua/blob/master/Assets/XLua/Doc/hotfix.md常见问题解答:https://github.com/Tencent/xLua/blob/master/Assets/
我们都知道,一个三维场景的画面的好坏,百分之四十取决于模型,百分之六十取决于贴图,可见贴图在画面中所占的重要性。在这里我将列举一些贴图,并且初步阐述其概念,理解原理的基础上制作贴图,也就顺手多了。我在这里主要列举几种UNITY3D中常用的贴图,与大家分享,希望对大家有帮助。01 首先