当前位置: 首页 > news >正文

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

相关文章:

  • unity3D调用外接摄像头,保存图片、不使用截屏方式
  • Unity3D中Find的用法
  • Unity3D中世界坐标转换到NGUI坐标
  • Window8.1+VS2013+Python+cocos2d-x-3.2
  • Java环境配置好之后,cnd窗口Java可以执行,但是Javac不能执行
  • cocos2d-x import org.cocos2dx.lib cannot be resolved
  • C#字符串处理:裁剪,替换,移除
  • NGUI 创建自定义按钮并添加按钮响应
  • Metaio中关于镜像问题
  • Unity3D+Arduino控制LED灯泡
  • 【好程序员训练营】Java线程学习
  • 【好程序员特训营】Java的Io操作
  • 【好程序员特训营】Java异常处理
  • 【好程序员特训营】Java字符串截取分割
  • 【好程序员特训营】Java线程同步初探
  • Babel配置的不完全指南
  • C++类的相互关联
  • co模块的前端实现
  • CSS选择器——伪元素选择器之处理父元素高度及外边距溢出
  • Git 使用集
  • webpack+react项目初体验——记录我的webpack环境配置
  • 基于HAProxy的高性能缓存服务器nuster
  • 聊聊directory traversal attack
  • 使用 Xcode 的 Target 区分开发和生产环境
  • 与 ConTeXt MkIV 官方文档的接驳
  • 云大使推广中的常见热门问题
  • 【运维趟坑回忆录】vpc迁移 - 吃螃蟹之路
  • (16)Reactor的测试——响应式Spring的道法术器
  • (3)(3.2) MAVLink2数据包签名(安全)
  • (env: Windows,mp,1.06.2308310; lib: 3.2.4) uniapp微信小程序
  • (poj1.2.1)1970(筛选法模拟)
  • (poj1.3.2)1791(构造法模拟)
  • (安全基本功)磁盘MBR,分区表,活动分区,引导扇区。。。详解与区别
  • (附源码)ssm失物招领系统 毕业设计 182317
  • (免费领源码)python#django#mysql公交线路查询系统85021- 计算机毕业设计项目选题推荐
  • (南京观海微电子)——I3C协议介绍
  • (三十五)大数据实战——Superset可视化平台搭建
  • (转)ABI是什么
  • (转)C#调用WebService 基础
  • (转载)VS2010/MFC编程入门之三十四(菜单:VS2010菜单资源详解)
  • *++p:p先自+,然后*p,最终为3 ++*p:先*p,即arr[0]=1,然后再++,最终为2 *p++:值为arr[0],即1,该语句执行完毕后,p指向arr[1]
  • *上位机的定义
  • .net 生成二级域名
  • .net利用SQLBulkCopy进行数据库之间的大批量数据传递
  • /3GB和/USERVA开关
  • ??javascript里的变量问题
  • [ 数据结构 - C++] AVL树原理及实现
  • [100天算法】-不同路径 III(day 73)
  • [16/N]论得趣
  • [Angular] 笔记 20:NgContent
  • [C# 网络编程系列]专题六:UDP编程
  • [C#]获取指定文件夹下的所有文件名(递归)
  • [Contest20180313]灵大会议
  • [CQOI 2010]扑克牌
  • [CUDA手搓]从零开始用C++ CUDA搭建一个卷积神经网络(LeNet),了解神经网络各个层背后算法原理