码迷,mamicode.com
首页 > 编程语言 > 详细

【小松教你手游开发】【系统模块开发】unity 数据储存到本地为二进制文件(聊天记录本地储存)

时间:2016-08-04 19:27:21      阅读:272      评论:0      收藏:0      [点我收藏+]

标签:

unity游戏开发中有很多需要把数据储存到本地,官方有好几个方式可以使用,下面简单介绍一下。

一、Stream::Write,Stream::WriteLine

这个方法是打开数据流就开始写字符串,可以指定长度写,也可以一行一行的写。具体参考http://blog.csdn.net/dingxiaowei2013/article/details/19084859和雨松大神的http://www.xuanyusong.com/archives/1069

这种方法最简单,一行一行的写,一行一行的读,都已String的形式写下来,可以中午可以英文。

缺点是不是二进制文件,不好做数据截断获取,比如你想把一个数据包保存下来,中间的各种数据需要你在字符串中写标记符进行切分。

 

二、[System.Serializable]标记,BinaryFormatter或xml写入

把自己的数据类型标记成可序列化数据二进制文件,用BinaryFormatter来进行写入读取操。具体参考http://bbs.9ria.com/thread-417373-1-1.html

这种方法也比较简单,数据按数据结构存放,数据不用做解析直接按数据结构使用

缺点是只能存放一个数据,每次写入读取都是一个数据,并不适合大多数情况(有一种用哈希表的形式进行拓展,不好用不说据说在ios上还有问题)

 

三、自己做数据解析,BinaryWriter写入

可以定义一个数据结构,这个结构里面的确定这个数据结构里的每个变量的数据类型,如果有字符串还需要获取字符串长度放在字符串前面

也就是一般网络传输的方式。

我现在项目用的就是这个方法,具体我会在后面贴上代码。

这种方法比较麻烦,需要自己定义数据结构和确定好每个数据结构的变量数据类型,字符串需要计算长度,但是这种方法可以适合任何场景。并且数据不需要换行只管一直写入,

而且这种方面解决上面两个方式的缺点

这个方法还有一个缺点是如果数据结构改了需要改读取和写入数据的方法。

 

因为想着写入本地序列化不只是我一个需求,需要可拓展性。

跟进上面这些我对类结构进行了一些安排

 

下面是代码和解释

我写的是一个保存聊天记录的功能

数据结构基类(暂时里面为空。。。虽然没有东西但是总觉得以后需要所以建了个基类)

 

[csharp] view plain copy
 
 技术分享技术分享
  1. using UnityEngine;  
  2. using System.Collections;  
  3.   
  4. public class SerializeDataBase  
  5. {  
  6.   
  7. }  

 

 

聊天数据的数据结构

[csharp] view plain copy
 
 技术分享技术分享
  1. using UnityEngine;  
  2. using System.Collections;  
  3.   
  4. public class ChatSerializeData : SerializeDataBase  
  5. {  
  6.     public long timeStamp;  
  7.     public int senderID;  
  8.     public int receiverID;  
  9.     //public short contentLength //这里有16位代表下面的字符串长度  
  10.     public string content;  
  11.   
  12. }  



序列化的基类,写成单例

因为是io,所有写到一个线程里,用队列的存储,读写都在同一个线程中 

[csharp] view plain copy
 
 技术分享技术分享
  1. using UnityEngine;  
  2. using System.Collections;  
  3. using System.Collections.Generic;  
  4. using System.Threading;  
  5.   
  6. public class SerializeClassBase<T, S> where T : SerializeDataBase where S : new()  
  7. {  
  8.     public delegate void LocalDataReadDelegate(List<T> dataList);  
  9.     Queue<LocalDataReadDelegate> m_onReadDoneDelegateQueue = new Queue<LocalDataReadDelegate>();  
  10.   
  11.     Thread m_thread;  
  12.     bool m_threadStart = true;  
  13.   
  14.     Queue<T> m_writeThreadQueue = new Queue<T>();  
  15.     Queue<string> m_readThreadQueue = new Queue<string>();  
  16.   
  17.   
  18.     private static S m_instance;  
  19.     public static S Instance  
  20.     {  
  21.         get  
  22.         {  
  23.             if (m_instance == null)  
  24.                 m_instance = new S();  
  25.             return m_instance;  
  26.         }  
  27.     }  
  28.   
  29.     public SerializeClassBase()  
  30.     {  
  31.         m_thread = new Thread(ThreadAsync);  
  32.         m_thread.Start();  
  33.     }  
  34.   
  35.     protected virtual void WriteFile(T data)  
  36.     {  
  37.   
  38.     }  
  39.   
  40.     protected virtual List<T> ReadFile(string arg)  
  41.     {  
  42.         return null;  
  43.     }  
  44.   
  45.     public void SaveData(T data)  
  46.     {  
  47.         m_writeThreadQueue.Enqueue(data);  
  48.     }  
  49.   
  50.     public void GetData(string arg,LocalDataReadDelegate del)  
  51.     {  
  52.         m_readThreadQueue.Enqueue(arg);  
  53.         m_onReadDoneDelegateQueue.Enqueue(del);  
  54.     }  
  55.   
  56.     void ThreadAsync()  
  57.     {  
  58.         while (m_threadStart)  
  59.         {  
  60.   
  61.             while(m_readThreadQueue.Count > 0)  
  62.             {  
  63.                 m_onReadDoneDelegateQueue.Dequeue()(ReadFile(m_readThreadQueue.Dequeue()));  
  64.             }  
  65.   
  66.   
  67.             while (m_writeThreadQueue.Count > 0)  
  68.             {  
  69.                 WriteFile(m_writeThreadQueue.Dequeue());  
  70.             }  
  71.   
  72.   
  73.             Thread.Sleep(1000);  
  74.         }  
  75.     }  
  76.   
  77.     public void StopThread()  
  78.     {  
  79.         m_threadStart = false;  
  80.     }  
  81. }  


因为写入的时候通常不需要知道是否完成,但是读取的时候需要知道什么时候读取完成,

 

所有这里读取写的是通过回调的形式返回

 

聊天存储的类,二进制读写的子类

 

[csharp] view plain copy
 
 技术分享技术分享
  1. using UnityEngine;  
  2. using System.Collections;  
  3. using System.Collections.Generic;  
  4. using System.IO;  
  5. using System;  
  6. using System.Runtime.Serialization.Formatters.Binary;  
  7. using System.Text;  
  8. using System.Threading;  
  9.   
  10. public class ChatSerializeClass : SerializeClassBase<ChatSerializeData, ChatSerializeClass>  
  11. {  
  12.     int MaximumFileCount = 5;  
  13.   
  14.     string folderName = Application.persistentDataPath + "//" + "Chat";  
  15.   
  16.     //Queue<string> m_localFileNameList = new Queue<string>();  
  17.     Dictionary<int, Queue<string>> m_localFileNameList = new Dictionary<int, Queue<string>>();  
  18.   
  19.   
  20.     public ChatSerializeClass()  
  21.     {  
  22.         if (!Directory.Exists(folderName))  
  23.         {  
  24.             Directory.CreateDirectory(folderName);  
  25.         }  
  26.     }  
  27.   
  28.     protected override void WriteFile(ChatSerializeData data)  
  29.     {  
  30.         //按聊天的好友id创建文件夹  
  31.         int targetID;  
  32.         if (data.senderID != LoginManager.Instance.PlayerData.CharID)  
  33.             targetID = data.senderID;  
  34.         else  
  35.             targetID = data.receiverID;  
  36.   
  37.         string folderNameWithID = folderName + "/" + targetID;  
  38.         if (!Directory.Exists(folderNameWithID))  
  39.         {  
  40.             Directory.CreateDirectory(folderNameWithID);  
  41.         }  
  42.   
  43.   
  44.   
  45.         //储存文本  
  46.         if (data == null)  
  47.             return;  
  48.   
  49.         string fileName = new DateTime(data.timeStamp).ToString("yyyyMMdd");  
  50.         FileStream fs = new FileStream(folderNameWithID + "/" + fileName, FileMode.Append);  
  51.         BinaryWriter bw = new BinaryWriter(fs);  
  52.   
  53.         bw.Write(data.timeStamp);  
  54.         bw.Write(data.senderID);  
  55.         bw.Write(data.receiverID);  
  56.         bw.Write(Encoding.UTF8.GetByteCount(data.content));  
  57.         bw.Write(Encoding.UTF8.GetBytes(data.content));  
  58.   
  59.         bw.Close();  
  60.         fs.Close();  
  61.         fs.Dispose();  
  62.   
  63.   
  64.         CDebug.Log("senderID:" + data.senderID + "--------");  
  65.     }  
  66.   
  67.     protected override List<ChatSerializeData> ReadFile(string fileName)  
  68.     {  
  69.         List<ChatSerializeData> dataList = new List<ChatSerializeData>();  
  70.   
  71.         FileStream fs = new FileStream(fileName, FileMode.Open);  
  72.         BinaryReader br = new BinaryReader(fs);  
  73.   
  74.         try  
  75.         {  
  76.             while (true)  
  77.             {  
  78.                 ChatSerializeData data = new ChatSerializeData();  
  79.                 data.timeStamp = br.ReadInt64();  
  80.                 data.senderID = br.ReadInt32();  
  81.                 data.receiverID = br.ReadInt32();  
  82.                 int contentLength = br.ReadInt32();  
  83.                 data.content = Encoding.UTF8.GetString(br.ReadBytes(contentLength));  
  84.                 dataList.Add(data);  
  85.             }  
  86.         }  
  87.         catch (Exception)  
  88.         {  
  89.             CDebug.Log("ReadFile:" + fileName + "----done!");  
  90.         }  
  91.         br.Close();  
  92.         fs.Close();  
  93.         fs.Dispose();  
  94.   
  95.   
  96.         return dataList;  
  97.     }  
  98.   
  99.     /// <summary>  
  100.     /// 通过好友id找到聊天记录,一次获取一天的聊天信息   
  101.     /// </summary>  
  102.     /// <param name="id"></param>  
  103.     public void GetDataByID(int id, LocalDataReadDelegate del)  
  104.     {  
  105.         string folderNameWithID = folderName + "/" + id;  
  106.   
  107.         //判读是否有该id的聊天数据  
  108.         if (!Directory.Exists(folderNameWithID))  
  109.         {  
  110.             if (del != null)  
  111.                 del(null);  
  112.   
  113.             return;  
  114.         }  
  115.   
  116.         //判断是否已经读取该id的文件列表,读取并排序  
  117.         if(!m_localFileNameList.ContainsKey(id))  
  118.         {  
  119.             Queue<string> list = new Queue<string>();  
  120.             string[] fileList = Directory.GetFiles(folderNameWithID);  
  121.             for (int i = 0; i < fileList.Length; i++)  
  122.             {  
  123.                 list.Enqueue(fileList[i]);  
  124.             }  
  125.             list.Sorted<string>();  
  126.   
  127.             //如果超过5个删除  
  128.             if(list.Count > MaximumFileCount)  
  129.             {  
  130.                 int count = list.Count;  
  131.                 for (int i =0; i < count - MaximumFileCount; i++)  
  132.                 {  
  133.                     File.Delete(list.Dequeue());//写上删除逻辑  
  134.                 }  
  135.   
  136.             }  
  137.             list.Reversed<string>();  
  138.   
  139.             m_localFileNameList.Add(id, list);  
  140.         }  
  141.   
  142.         //读取文件  
  143.         if(m_localFileNameList[id].Count >0)  
  144.             GetData(m_localFileNameList[id].Dequeue(), del);  
  145.     }  
  146. }  


由于我的聊天读写功能再稍微复杂一点,需要按id按天数来保存,并且删除超过5天以上的聊天记录,所以实际逻辑并不需要这么多

 

 

实际上只需要继承并重写

[csharp] view plain copy
 
 技术分享技术分享
  1. </pre></p><p><pre name="code" class="csharp">    protected virtual void WriteFile(T data)  
  2.     {  
  3.   
  4.     }  
  5.   
  6.     protected virtual List<T> ReadFile(string arg)  
  7.     {  
  8.         return null;  
  9.     }  


读写函数,因为这个涉及到你的数据应该怎么个读写法,你的数据规则,所以这个需要自己去重写。

 

 

使用的方法就是

ChatSerialieClass.Instance.SaveData();

ChatSerialieClass.Instance.GetData();

 

只有像我聊天那样比较复杂的需求才需要另外写接口再调用上面的函数。

 

 

 

这样就可以做到需要的需求和方便其他人拓展

【小松教你手游开发】【系统模块开发】unity 数据储存到本地为二进制文件(聊天记录本地储存)

标签:

原文地址:http://www.cnblogs.com/chrisfxs/p/5737783.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!