unity3d 本地存储选择

来源:互联网 发布:数据行业 编辑:程序博客网 时间:2024/06/06 02:48

  最近给自己的小游戏弄好背包系统后,开始琢磨怎么保存到本地,我有三种选择方案:1.用excel格式保存 2.用sqlite保存 3.用json格式保存 excel优势是方便编辑,但对它不熟悉,sqlite在unity上坑比较多,所以最后选择用json保存。

  在unity5.3出来前,一直使用的是LitJson来解析。后来官方出了自己的JsonUtility,这两个都很简单、方便,但由于自己很懒,不想学新东西,所以还是使用的LitJson。

  我是参考这篇文章来做的:http://www.cnblogs.com/peiandsky/archive/2012/04/20/2459219.html

  1.将list转换成json格式

ArrayList list = new ArrayList ();
foreach (GameObject obj in objs) {Wuping wp = new Wuping ();wp.wp_name = obj.GetComponent<WupingDesc> ().wp_name;wp.wp_desc = obj.GetComponent<WupingDesc> ().wp_desc;wp.wp_num = obj.GetComponent<WupingDesc> ().wp_num;list.Add (wp);}string json = JsonMapper.ToJson (list);string fileName = Application.persistentDataPath + "//" + "test.text";JsonTool.CreateFile(fileName,json);

  里面Wuping类不是MonoBehaviour的子类,而WupingDesc类是MonoBehaviour的子类,所以要转换一下 即JsonMapper.ToJson(这里不能放MonoBehaviour子类的实例)

  2.将json字符串读出来

JsonData data = JsonMapper.ToObject (jsonStr);string wp_name = (string)data [i] ["wp_name"];

  3.补充:文件读取类(这个参考的这篇文章http://www.xuanyusong.com/archives/1069)

using System.Collections;using System.Collections.Generic;using System;using System.IO;public class JsonTool {// C#方法名要大写 和java不一样public static void CreateFile(string fileName,string content) {StreamWriter sw;FileInfo t = new FileInfo (fileName);//if (!t.Exists) {// 如果文件不存在就创建//sw = t.CreateText ();//} else {//sw = t.AppendText ();//}sw = t.CreateText ();sw.WriteLine (content);sw.Close ();sw.Dispose ();}public static string LoadFile(string fileName) {StreamReader sr = null;try {sr = File.OpenText(fileName);} catch(Exception e) {return null;}string line;string json = "";while( (line = sr.ReadLine()) != null ) {json += line;}sr.Close ();sr.Dispose ();return json;}}


  因为我之前都是做OC的,所以代码格式都是按照OC来写的,所以看上去有些怪。而且今天我才知道原来C#方法名首字母要大写。。。


0 0