Unity 保存和加载XML文件

 

 

保存工程的信息:比如游戏进程中的位置信息,对抗双方的个人信息等:

方法1:使用xml文件:

 xml文件要以UTF-8的格式存储;

 但是这样做会使得programmer 可以从脚本中控制xml文件中的所有的字符,包括xml文件中的语法命令字符,因此会带来不安全隐患;

 附上两段代码:

 A 这一段是我自己写的,将一个xml文件按照字符串读入;

虽然unity3d中的string类型说明中讲到保存的是unicode characters,但是实际上当xml文件比较大的时候,如果保存成unicode,就读不出来,如果保存成UTF-8就不存在这个问题;

C#版本:

              using UnityEngine;   
  1. using System.Collections;   
  2. using System.Xml;   
  3. using System.Xml.Serialization;   
  4. using System.IO;   
  5. using System.Text;   
  6. public class ReadXML: MonoBehaviour {  
  7.    
  8.  //store the read in file   
  9.  WWW statusFile;  
  10.    
  11.  //decide wether the reading of  xml has been finished  
  12.     bool isReadIn = false;  
  13.  // Use this for initialization  
  14.  IEnumerator Start () {//不能用void,否则没有办法使用yield  
  15.   isReadIn = false;  
  16.   yield return StartCoroutine(ReadIn());  
  17.   isReadIn = true;  
  18.  }  
  19.    
  20.  IEnumerator ReadIn()  
  21.  {  
  22.   yield return statusFile = new WWW("file:///D:/unity/rotationAndcolor/Assets/information/testxml.xml");//注意路径的写法  
  23.  }  
  24.    
  25.  // Update is called once per frame  
  26.  void Update () {  
  27.   if(isReadIn)  
  28.   {  
  29.    string statusData = statusFile.data;  
  30.    print(statusData.Length);  
  31.    }  
  32.  }  
  33.    
  34.  //get the parameters in the xml file  
  35.  void getPatameters(string _xmlString)  
  36.  {  
  37.   //_xmlString.[0]   
  38.   }  
  39.    
  40.  void postParameters()  
  41.  {  
  42.     
  43.   }  
  44. }  
  45. public class _GameSaveLoad: MonoBehaviour {   
  46.    // An example where the encoding can be found is at   
  47.    // http://www.eggheadcafe.com/articles/system.xml.xmlserialization.asp   
  48.    // We will just use the KISS method and cheat a little and use   
  49.    // the examples from the web page since they are fully described   
  50.       
  51.    // This is our local private members   
  52.    Rect _Save, _Load, _SaveMSG, _LoadMSG;   
  53.    bool _ShouldSave, _ShouldLoad,_SwitchSave,_SwitchLoad;   
  54.    string _FileLocation,_FileName;   
  55.    public GameObject _Player;   
  56.    UserData myData;   
  57.    string _PlayerName;   
  58.    string _data;   
  59.       
  60.    Vector3 VPosition;   
  61.       
  62.    // When the EGO is instansiated the Start will trigger   
  63.    // so we setup our initial values for our local members   
  64.    void Start () {   
  65.       // We setup our rectangles for our messages   
  66.       _Save=new Rect(10,80,100,20);   
  67.       _Load=new Rect(10,100,100,20);   
  68.       _SaveMSG=new Rect(10,120,400,40);   
  69.       _LoadMSG=new Rect(10,140,400,40);   
  70.           
  71.       // Where we want to save and load to and from   
  72.       _FileLocation=Application.dataPath;   
  73.       _FileName="SaveData.xml";   
  74.       
  75.       // for now, lets just set the name to Joe Schmoe   
  76.       _PlayerName = "Joe Schmoe";   
  77.           
  78.       // we need soemthing to store the information into   
  79.       myData=new UserData();   
  80.    }   
  81.       
  82.    void Update () {}   
  83.       
  84.    void OnGUI()   
  85.    {      
  86.          
  87.    //***************************************************   
  88.    // Loading The Player...   
  89.    // **************************************************         
  90.    if (GUI.Button(_Load,"Load")) {   
  91.          
  92.       GUI.Label(_LoadMSG,"Loading from: "+_FileLocation);   
  93.       // Load our UserData into myData   
  94.       LoadXML();   
  95.       if(_data.ToString() != "")   
  96.       {   
  97.         // notice how I use a reference to type (UserData) here, you need this   
  98.         // so that the returned object is converted into the correct type   
  99.         myData = (UserData)DeserializeObject(_data);   
  100.         // set the players position to the data we loaded   
  101.         VPosition=new Vector3(myData._iUser.x,myData._iUser.y,myData._iUser.z);                
  102.         _Player.transform.position=VPosition;   
  103.         // just a way to show that we loaded in ok   
  104.         Debug.Log(myData._iUser.name);   
  105.       }   
  106.       
  107.    }   
  108.       
  109.    //***************************************************   
  110.    // Saving The Player...   
  111.    // **************************************************      
  112.    if (GUI.Button(_Save,"Save")) {   
  113.                 
  114.      GUI.Label(_SaveMSG,"Saving to: "+_FileLocation);   
  115.      myData._iUser.x=_Player.transform.position.x;   
  116.      myData._iUser.y=_Player.transform.position.y;   
  117.      myData._iUser.z=_Player.transform.position.z;   
  118.      myData._iUser.name=_PlayerName;      
  119.             
  120.      // Time to creat our XML!   
  121.      _data = SerializeObject(myData);   
  122.      // This is the final resulting XML from the serialization process   
  123.      CreateXML();   
  124.      Debug.Log(_data);   
  125.    }   
  126.       
  127.       
  128.    }   
  129.       
  130.    /* The following metods came from the referenced URL */   
  131.    string UTF8ByteArrayToString(byte[] characters)   
  132.    {        
  133.       UTF8Encoding encoding = new UTF8Encoding();   
  134.       string constructedString = encoding.GetString(characters);   
  135.       return (constructedString);   
  136.    }   
  137.       
  138.    byte[] StringToUTF8ByteArray(string pXmlString)   
  139.    {   
  140.       UTF8Encoding encoding = new UTF8Encoding();   
  141.       byte[] byteArray = encoding.GetBytes(pXmlString);   
  142.       return byteArray;   
  143.    }   
  144.       
  145.    // Here we serialize our UserData object of myData   
  146.    string SerializeObject(object pObject)   
  147.    {   
  148.       string XmlizedString = null;   
  149.       MemoryStream memoryStream = new MemoryStream();   
  150.       XmlSerializer xs = new XmlSerializer(typeof(UserData));   
  151.       XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);   
  152.       xs.Serialize(xmlTextWriter, pObject);   
  153.       memoryStream = (MemoryStream)xmlTextWriter.BaseStream;   
  154.       XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());   
  155.       return XmlizedString;   
  156.    }   
  157.       
  158.    // Here we deserialize it back into its original form   
  159.    object DeserializeObject(string pXmlizedString)   
  160.    {   
  161.       XmlSerializer xs = new XmlSerializer(typeof(UserData));   
  162.       MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString));   
  163.       XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);   
  164.       return xs.Deserialize(memoryStream);   
  165.    }   
  166.       
  167.    // Finally our save and load methods for the file itself   
  168.    void CreateXML()   
  169.    {   
  170.       StreamWriter writer;   
  171.       FileInfo t = new FileInfo(_FileLocation+"//"+ _FileName);   
  172.       if(!t.Exists)   
  173.       {   
  174.          writer = t.CreateText();   
  175.       }   
  176.       else   
  177.       {   
  178.          t.Delete();   
  179.          writer = t.CreateText();   
  180.       }   
  181.       writer.Write(_data);   
  182.       writer.Close();   
  183.       Debug.Log("File written.");   
  184.    }   
  185.       
  186.    void LoadXML()   
  187.    {   
  188.       StreamReader r = File.OpenText(_FileLocation+"//"+ _FileName);   
  189.       string _info = r.ReadToEnd();   
  190.       r.Close();   
  191.       _data=_info;   
  192.       Debug.Log("File Read");   
  193.    }   
  194. }   
  195. // UserData is our custom class that holds our defined objects we want to store in XML format   
  196.  public class UserData   
  197.  {   
  198.     // We have to define a default instance of the structure   
  199.    public DemoData _iUser;   
  200.     // Default constructor doesn't really do anything at the moment   
  201.    public UserData() { }   
  202.       
  203.    // Anything we want to store in the XML file, we define it here   
  204.    public struct DemoData   
  205.    {   
  206.       public float x;   
  207.       public float y;   
  208.       public float z;   
  209.       public string name;   
  210.    }   

 

 

js 版本:

             import System;  
  1. import System.Collections;  
  2. import System.Xml;  
  3. import System.Xml.Serialization;  
  4. import System.IO;  
  5. import System.Text;  
  6. // Anything we want to store in the XML file, we define it here  
  7. class DemoData  
  8. {  
  9.     var x : float;  
  10.     var y : float;  
  11.     var z : float;  
  12.     var name : String;  
  13. }  
  14. // UserData is our custom class that holds our defined objects we want to store in XML format  
  15.  class UserData  
  16.  {  
  17.     // We have to define a default instance of the structure  
  18.    public var _iUser : DemoData = new DemoData();  
  19.     // Default constructor doesn't really do anything at the moment  
  20.    function UserData() { }  
  21. }  
  22. //public class GameSaveLoad: MonoBehaviour {  
  23. // An example where the encoding can be found is at  
  24. // http://www.eggheadcafe.com/articles/system.xml.xmlserialization.asp  
  25. // We will just use the KISS method and cheat a little and use  
  26. // the examples from the web page since they are fully described  
  27. // This is our local private members  
  28. private var _Save : Rect;  
  29. private var _Load : Rect;  
  30. private var _SaveMSG : Rect;  
  31. private var _LoadMSG : Rect;  
  32. //var _ShouldSave : boolean;  
  33. //var _ShouldLoad : boolean;  
  34. //var _SwitchSave : boolean;  
  35. //var _SwitchLoad : boolean;  
  36. private var _FileLocation : String;  
  37. private var _FileName : String = "SaveData.xml";  
  38. //public GameObject _Player;  
  39. var _Player : GameObject;  
  40. var _PlayerName : String = "Joe Schmoe";  
  41. private var myData : UserData;  
  42. private var _data : String;  
  43. private var VPosition : Vector3;  
  44. // When the EGO is instansiated the Start will trigger  
  45. // so we setup our initial values for our local members  
  46. //function Start () {  
  47. function Awake () {   
  48.       // We setup our rectangles for our messages  
  49.       _Save=new Rect(10,80,100,20);  
  50.       _Load=new Rect(10,100,100,20);  
  51.       _SaveMSG=new Rect(10,120,200,40);  
  52.       _LoadMSG=new Rect(10,140,200,40);  
  53.          
  54.       // Where we want to save and load to and from  
  55.       _FileLocation=Application.dataPath;  
  56.         
  57.             
  58.       // we need soemthing to store the information into  
  59.       myData=new UserData();  
  60.    }  
  61.      
  62. function Update () {}  
  63.      
  64. function OnGUI()  
  65. {     
  66.    // ***************************************************  
  67.    // Loading The Player...  
  68.    // **************************************************         
  69.    if (GUI.Button(_Load,"Load")) {  
  70.         
  71.       GUI.Label(_LoadMSG,"Loading from: "+_FileLocation);  
  72.       // Load our UserData into myData  
  73.       LoadXML();  
  74.       if(_data.ToString() != "")  
  75.       {  
  76.          // notice how I use a reference to type (UserData) here, you need this  
  77.          // so that the returned object is converted into the correct type  
  78.          //myData = (UserData)DeserializeObject(_data);  
  79.          myData = DeserializeObject(_data);  
  80.          // set the players position to the data we loaded  
  81.          VPosition=new Vector3(myData._iUser.x,myData._iUser.y,myData._iUser.z);               
  82.          _Player.transform.position=VPosition;  
  83.          // just a way to show that we loaded in ok  
  84.          Debug.Log(myData._iUser.name);  
  85.       }  
  86.      
  87.    }  
  88.      
  89.    // ***************************************************  
  90.    // Saving The Player...  
  91.    // **************************************************     
  92.    if (GUI.Button(_Save,"Save")) {  
  93.               
  94.       GUI.Label(_SaveMSG,"Saving to: "+_FileLocation);  
  95.       //Debug.Log("SaveLoadXML: sanity check:"+ _Player.transform.position.x);  
  96.         
  97.       myData._iUser.x = _Player.transform.position.x;  
  98.       myData._iUser.y = _Player.transform.position.y;  
  99.       myData._iUser.z = _Player.transform.position.z;  
  100.       myData._iUser.name = _PlayerName;     
  101.           
  102.       // Time to creat our XML!  
  103.       _data = SerializeObject(myData);  
  104.       // This is the final resulting XML from the serialization process  
  105.       CreateXML();  
  106.       Debug.Log(_data);  
  107.    }  
  108. }  
  109.      
  110. /* The following metods came from the referenced URL */  
  111. //string UTF8ByteArrayToString(byte[] characters)  
  112. function UTF8ByteArrayToString(characters : byte[] )  
  113. {       
  114.    var encoding : UTF8Encoding  = new UTF8Encoding();  
  115.    var constructedString : String  = encoding.GetString(characters);  
  116.    return (constructedString);  
  117. }  
  118. //byte[] StringToUTF8ByteArray(string pXmlString)  
  119. function StringToUTF8ByteArray(pXmlString : String)  
  120. {  
  121.    var encoding : UTF8Encoding  = new UTF8Encoding();  
  122.    var byteArray : byte[]  = encoding.GetBytes(pXmlString);  
  123.    return byteArray;  
  124. }  
  125.      
  126.    // Here we serialize our UserData object of myData  
  127.    //string SerializeObject(object pObject)  
  128. function SerializeObject(pObject : Object)  
  129. {  
  130.    var XmlizedString : String  = null;  
  131.    var memoryStream : MemoryStream  = new MemoryStream();  
  132.    var xs : XmlSerializer = new XmlSerializer(typeof(UserData));  
  133.    var xmlTextWriter : XmlTextWriter  = new XmlTextWriter(memoryStream, Encoding.UTF8);  
  134.    xs.Serialize(xmlTextWriter, pObject);  
  135.    memoryStream = xmlTextWriter.BaseStream; // (MemoryStream)  
  136.    XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());  
  137.    return XmlizedString;  
  138. }  
  139.    // Here we deserialize it back into its original form  
  140.    //object DeserializeObject(string pXmlizedString)  
  141. function DeserializeObject(pXmlizedString : String)     
  142. {  
  143.    var xs : XmlSerializer  = new XmlSerializer(typeof(UserData));  
  144.    var memoryStream : MemoryStream  = new MemoryStream(StringToUTF8ByteArray(pXmlizedString));  
  145.    var xmlTextWriter : XmlTextWriter  = new XmlTextWriter(memoryStream, Encoding.UTF8);  
  146.    return xs.Deserialize(memoryStream);  
  147. }  
  148.    // Finally our save and load methods for the file itself  
  149. function CreateXML()  
  150. {  
  151.    var writer : StreamWriter;  
  152.    //FileInfo t = new FileInfo(_FileLocation+"//"+ _FileName);  
  153.    var t : FileInfo = new FileInfo(_FileLocation+"/"+ _FileName);  
  154.    if(!t.Exists)  
  155.    {  
  156.       writer = t.CreateText();  
  157.    }  
  158.    else  
  159.    {  
  160.       t.Delete();  
  161.       writer = t.CreateText();  
  162.    }  
  163.    writer.Write(_data);  
  164.    writer.Close();  
  165.    Debug.Log("File written.");  
  166. }  
  167.      
  168. function LoadXML()  
  169. {  
  170.    //StreamReader r = File.OpenText(_FileLocation+"//"+ _FileName);  
  171.    var r : StreamReader = File.OpenText(_FileLocation+"/"+ _FileName);  
  172.    var _info : String = r.ReadToEnd();  
  173.    r.Close();  
  174.    _data=_info;  
  175.    Debug.Log("File Read");  
  176. }  
  177. //} 

 

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

 

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

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值