unity

来源:互联网 发布:c语言flag的用法 编辑:程序博客网 时间:2024/05/02 01:44

转载连接: http://blog.csdn.net/u013236878/article/details/52443157?locationNum=4&fps=1


目标:实现数据存储为二进制文件,然后通过二进制文件解析数据。

目标分为三个阶段:1、将数据结构转化为二进制(至于数据是怎样读取进来的这个就不说了,因为方式比较多,但是读取进来一定都会以特定的数据结构形式来保存)。2、加载二进制文本。3、加载为对应的数据结构。


阶段一:将数据结构转化为二进制有两种方式:1:利用C#的BinaryWrite,2:使用函数把数据转化成byte数组,然后在写入。

方法1:

[csharp] view plain copy
  1. public bool SaveBinaryFile(string _path, string _name, TextAsset t){  
  2.           
  3.         string content = t.text;  
  4.       
  5.         //二进制文件流信息  
  6.         BinaryWriter bw = new BinaryWriter(new FileStream (_path + _name, FileMode.Create));;  
  7.   
  8.         FileStream fs = new FileStream (_path + _name, FileMode.Create);  
  9.   
  10.         try {  
  11.   
  12.             bw = new BinaryWriter(new FileStream (_path + _name, FileMode.Create));  
  13.   
  14.   
  15.         }catch(IOException e){  
  16.   
  17.             Debug.Log (e.Message);  
  18.   
  19.         }  
  20.         try {  
  21.   
  22.             bw.Write(content);  
  23.   
  24.         }catch(IOException e){  
  25.   
  26.             Debug.Log (e.Message);  
  27.   
  28.         }  
  29.         debugInfo += "文件创建成功!\n";  
  30.   
  31.         return true;  
  32.   
  33.     }  
说明:这种方法代码也没几行,方式也很好理解,我把过程封装成函数,传入路径和文件名即可(温馨提示:unity里面二进制存在StreamingAssets文件夹里面,若不懂可百度,有很多资源)。

为了让大家更好的理解我把路径贴出来:

[csharp] view plain copy
  1. private string name = "1.bytes";  
  2.   
  3. public static readonly string path = Application.streamingAssetsPath + "/";  

方法2:

[csharp] view plain copy
  1. string path = Application.streamingAssetsPath + "/";  
  2. string name = "2.bytes";  
  3. int a = 15;  
  4. byte[] b = BitConverter.GetBytes (a);  
  5. File.WriteAllBytes (path + name, b);  
说明:这种方法简单方便,利用System.Text下的BitConverter将其他类型的转化为二进制类型[特殊:不包括String类型的转化,string转化用Encoding.UTF8.GetBytes即可]。


这样阶段一就完成了。


阶段二:

加载二进制文本采用www加载,目前我知道唯一简单方便的加载方式,如果有更好的加载方式还请指教。

用www加载需要用到协程,如果对协程不是很懂的同学请自行查询(记得以前写过一篇但是没找到,有时间也会整理一篇)。下面是加载代码。

[csharp] view plain copy
  1. IEnumerator wwwLoad(string _path, Action<byte[]> action){  
  2.  
  3.         #if UNITY_EDITOR || UNITY_IOS  
  4.         _path = "file://" + _path;  
  5.         #endif  
  6.           
  7.         WWW www = new WWW (_path);  
  8.   
  9.         yield return www;  
  10.   
  11.         action (www.bytes);  
  12.     }  

注意点:下载的路径有所变化,详细了解可以去看看Unity的平台路径,因为与本文无关,不多说了。这里我用了回调,只是习惯,当然也可以等WWW下载完成后自行调用其他函数。


阶段三:使用BinaryReader类解析二进制文件

[csharp] view plain copy
  1. public void readByte(byte[] b){  
  2.     using (BinaryReader br = new BinaryReader(new MemoryStream(b))){  
  3.         int f = br.ReadInt32 ();  
  4.         Debug.Log (f);  
  5.     }  
  6. }  
只需要使用使BinaryReader类中的函数来读取对一个类型的数据就可以了。



至此,任务完成。