一、前言

      在Unity中读写Json文件已经有非常好的工具,可以将Json文件和结构体数据进行相互转换,如图1所示,在Unity Asset Store中搜JSON.NET可以找到该插件,非常好用。我在此插件的基础上,融合了Windows的文件窗口,即打开和存储Json文件的时候可

图1

以获取Windows的窗口,选择保存和读取Json文件的路径。最后,实现了在Android上的读写Json文件。

二、实现

2.1、实现读写文件的窗口

代码如下:该类提供了一个Open_WindowFile方法,当参数"isSaveFile"为true时弹出窗口保存文件,false时弹出窗口打开文件,默认为false。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Runtime.InteropServices;//调用外部库,需要引用命名空间
using System;
using System.Threading;public class Global_Windows  {public static Global_Windows M_Instance{get{if (_instance == null){_instance = new Global_Windows();}return _instance;}}private openFileName ofn = new openFileName();private static Global_Windows _instance;[DllImport("User32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]public static extern int MessageBox(IntPtr handle, String message, String title, int type);//具体方法[DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]public static extern bool GetOpenFileName([In, Out] openFileName ofn);[DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]public static extern bool GetSaveFileName([Out, In] openFileName ofn);/// <summary>/// 打开某个格式的文件,并返回该文件的地址/// </summary>/// <param name="dataType">该文件的格式</param>/// <param name="isSaveFile">true为保存文件,false为只是打开文件,默认为false</param>/// <returns></returns>public string Open_WindowFile(string dataType,bool isSaveFile=false){string tempURL = string.Empty;ofn.structSize = Marshal.SizeOf(ofn);ofn.filter = dataType+"\0*."+ dataType + "*\0\0";// ofn.filter = "json\0*.json*\0\0";ofn.file = new string(new char[256]);ofn.maxFile = ofn.file.Length;ofn.fileTittle = new string(new char[64]);ofn.maxFileTittle = ofn.fileTittle.Length;string path = Application.streamingAssetsPath;path = path.Replace('/', '\\');ofn.initialDir = path;ofn.tittle = "Open Project";ofn.defExt = dataType;ofn.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000200 | 0x00000008;if (isSaveFile&& GetSaveFileName(ofn)){tempURL = ofn.file;}else if(!isSaveFile&&GetOpenFileName(ofn)){tempURL = ofn.file;}return tempURL;}
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class openFileName
{public int structSize = 0;public IntPtr digOwner = IntPtr.Zero;public IntPtr instance = IntPtr.Zero;public String filter = null;public String customFilter = null;public int maxCustFilter = 0;public int filterIndex = 0;public String file = null;public int maxFile = 0;public String fileTittle = null;public int maxFileTittle = 0;public String initialDir = null;public String tittle = null;public int flags = 0;public short fileoffset = 0;public short fileExtension = 0;public String defExt = null;public IntPtr custData = IntPtr.Zero;public IntPtr hook = IntPtr.Zero;public String templataName = null;public IntPtr reservedPtr = IntPtr.Zero;public int resveredInt = 0;public int flagsEx = 0;
}

2.2、实现Json文件的读写

代码如下:保存Json文件的时候先打开窗口获取保存文件的类型和路径,然后将结构体数据序列化成字符串,使用JsonConvert.SerializeObject方法将数据序列化。下面的代码可以序列化结构体中的数组或列表。读取Json文件的时候,首先会判断路径是否为

    /// <summary>/// 将结构体数据保存成JSON文件/// </summary>/// <param name="JSONFilePath"></param>/// <param name="data"></param>public static bool SaveData_JSON(object data){bool isSaveSucced = true;string JSONFilePath = Global_Windows.M_Instance.Open_WindowFile("json", true);#region 将结构体添加数据转换成JSON文件并存储try{FileInfo file = new FileInfo(JSONFilePath);//判断有没有文件,有则打开文件,,没有创建后打开文件StreamWriter sw = file.CreateText();string json = string.Empty;var settings = new JsonSerializerSettings(){TypeNameHandling = TypeNameHandling.All};json = JsonConvert.SerializeObject(data, settings);//   Debug.Log(json);//将转换好的字符串存进文件,sw.WriteLine(json);//注意释放资源sw.Close();sw.Dispose();}catch (Exception e){Debug.Log(e.Message);isSaveSucced = false;}return isSaveSucced;#endregion}/// <summary>/// 读取文件夹里的JSON文件,并转换成对应的结构体,/// 默认没有路径的会自动打开文件夹选择窗口/// </summary>/// <typeparam name="T"></typeparam>/// <returns></returns>public static T ReadData_JSON<T>(string jsonURL = null){T tempT = default(T);string JSONFilePath = jsonURL;
#if UNITY_STANDALONE_WIN || UNITY_EDITORif (null == JSONFilePath){JSONFilePath = Global_Windows.M_Instance.Open_WindowFile("json", false);}
#endiftry{string tempStrData = string.Empty;//#if UNITY_STANDALONE_WIN || UNITY_EDITOR//            StreamReader sr = new StreamReader(JSONFilePath, Encoding.UTF8);//安卓平台不能使用这个读取只能使用www//            tempStrData = sr.ReadToEnd();WWW www = new WWW(JSONFilePath);while (!www.isDone){// Debug.Log("正在读取!");}tempStrData = www.text;if (tempStrData.Length == 0 || string.Empty == tempStrData || null == tempStrData){
#if UNITY_STANDALONE_WIN || UNITY_EDITORGlobal_Windows.MessageBox(IntPtr.Zero, "JSON文件内容为空!", "确认", 0);
#endifDebug.Log("JSON文件内容为空!");return tempT;}var settings = new JsonSerializerSettings(){TypeNameHandling = TypeNameHandling.All};tempT = JsonConvert.DeserializeObject<T>(tempStrData, settings);//   Debug.Log(tempStrData);}catch (Exception e){Debug.Log(e.Message);
#if UNITY_STANDALONE_WIN || UNITY_EDITORGlobal_Windows.MessageBox(IntPtr.Zero, "读取JSON异常" + e.Message, "确认", 0);
#endifreturn tempT;}//  Global_Windows.MessageBox(IntPtr.Zero, "读取JSON数据成功", "确认", 0);return tempT;}

空,如果为空就开启窗口读取选择Json文件读取,如果不为空则不弹窗直接读取,非常方便。 另外,读写数据异常的时候会弹出Windows的消息窗口,代码如下:

 Global_Windows.MessageBox(IntPtr.Zero, "读取JSON异常" + e.Message, "确认", 0);

这个窗口时独立于Unity的,如果想单独使用在工程中也可以直接像上面那样调用。

2.3、规范Json文件的保存路径

为了将Json文件的读写路径都统一到指定的路径下,还需要增加一个统一路径的代码,如下:这个路可以在安卓系统上运行且读写Json文件,在Winddows下的路径为和工程同级目录

    /// <summary>/// 获取跟工程相同目录的路径,如“E:/ZXB/MyProject/Asset/",去掉后面两个就得到和工程同级的目录为:“E:/ZXB”/// </summary>/// <returns></returns>private static string GetCurProjectFilePath(){string strPath = string.Empty;
#if UNITY_ANDROIDstrPath = "file:///storage/emulated/0/";
#elif UNITY_STANDALONE_WIN || UNITY_EDITORstring[] strTempPath = Application.dataPath.Split('/');//去掉后面两个,获取跟工程相同目录的路径,如“E:/ZXB/MyProject/Asset/",去掉后面两个就得到和工程同级的目录为:“E:/ZXB”for (int i = 0; i < strTempPath.Length - 2; i++){strPath += strTempPath[i] + "/";}
#endifreturn strPath;}

三、总结

3.1、考虑Json文件序列化数组或列表的时候要注意参数设置为TypeNameHandling.All;

3.2、安卓平台读取Json文件的时候只能用WWW类来获取。

Unity实用小工具或脚本——读写Json工具相关推荐

  1. Unity实用小工具或脚本—以对象方式访问MySql数据库

    一.前言         以对象方式处理MySql数据库顾名思义就是可以将每个数据库表作为一个类,没一条数据作为一个对象来进行操作,大致思路和我上一篇文章类似,这里不再赘述.文章后有资源下载地址,所使 ...

  2. Unity 实用小技巧

    1.Project 窗口中搜索的使用 键入多个搜索词,缩小搜索范围,例如沿海场景,则会查找同时包含'沿海'和'场景'的名称 t:按指定类型过滤,l:按标签过滤,v: 点击按钮'五星',可以将当前检索指 ...

  3. Unity实用小工具或脚本—3D炫酷UI篇(一)

    一.前言 最近做AR和VR的项目,经常需要用到3D的UI,特意将最近自己捣鼓的这个UI的东西写下来.效果如图所示:主要的动画和素材也是借鉴了 第三方的插件"HoloUIExample&quo ...

  4. Unity实用小工具或脚本——可折叠伸缩的多级(至少三级)内容列表(类似于Unity的Hierarchy视图中的折叠效果)

    目录 一.前言 二.实现 2.1.创建ScrollView 2.2.制作层级预设体BaseLevelPartObj 2.3.设置该预设体的初始化处理方法 2.4.读取Hierarchy的内容并创建UI ...

  5. Unity实用小工具或脚本——可折叠伸缩的多级列表二(带搜索功能)

    一.前言 继上篇可折叠伸缩的多级(至少三级)内容列表实现了类似于Unity的Unity的Hierarchy视图中的折叠效果之后,我寻思的丰富一下该工具的功能,不保证说完全的复制Unity的Hierar ...

  6. Unity实用小工具或脚本——XML工具

    一.前言 这篇文章,早在游戏蛮牛的专栏里就写过,一直在使用这个工具,稍微修改了下.在我们的项目中经常会用到XML来存储一些工程中的设置,而对XML的操作无非就是增删改查四个操作,代码虽然不多,但是使用 ...

  7. Unity实用小工具或脚本——录屏工具

    一.前言 本文要讲的录屏不是使用Unity自带的那个截屏方法,因为unity自带的都只能截取unity程序本身显示的画面内容,至于unity程序之外的内容,如电脑桌面上的其他的程序内容是无法录屏的.本 ...

  8. Unity实用小工具或脚本——智能包住任意多个物体的碰撞体

    一.前言 有些模型是我们在Unity中进行组合得到的一个模块,这个时候不可能再让美术给加碰撞体,需要用代码智能给其加碰撞体,如图1所示:任意的多个物体组成的一个综合物体最后都可以给它加上合适的碰撞体, ...

  9. Unity实用小工具或脚本——3D物体带坐标轴的拖拽

    一.前言 我们最近要做一个线路的规划编辑,并且是在三维场景中,编辑完就立马能用.立马能用还好说,有特别多的轮子可以用,在三维场景中实时编辑就有点意思了.其实功能就是类似于在Unity的编辑界面操作一个 ...

最新文章

  1. dede问答模块 那个php文件相对重要,DEDE问答(ask)模块游客匿名提问和解答
  2. struts2中各版本jar包需求及配置设置
  3. [JAVA][算法] [字符串匹配]KMP
  4. SAP License:FICO面试问题
  5. Vue.js 学习笔记 七 控制样式
  6. Spring Boot实现动态数据库配置
  7. centos7 java 1.8_Centos7下安装Java JDK 1.8
  8. 学习笔记(26):NumPy数据分析-NumPy 统计函数-var方差
  9. ppt如何替换其他mo ban_相见恨晚的10个PPT制作小技巧!提高你的PPT制作效率
  10. Tensorflow概念详解
  11. 哈工大CSAPP大作业:程序人生-Hello’s P2P
  12. 微信开发学习二 -- 微信开发入门(简单demo)
  13. 概率论与数理统计 1 Overview and Descriptive Statistics(概述和描述性统计) (上篇)
  14. 人工智能的学习路线规划
  15. 浅谈BIM技术在“智慧工地”建设中的应用
  16. 如何用空气质量查询API接口进行快速开发
  17. 海康视频监控接入心得
  18. 时间戳转成日期,解决日期1970年的问题
  19. JAVA基础知识总结:一到二十二全部总结
  20. 迅雷register脚本

热门文章

  1. Adobe Zii使用方法
  2. 树莓派远程连接工具VNC使用教程
  3. 哼唱识别(query by humming)
  4. 画出spi输出bdh数据总线时序图_单片机张毅刚课后习题答案.docx
  5. 2D Conforming Triangulations
  6. u盘和计算机无法连接不上,U盘连接不上电脑怎么办
  7. 数字藏品平台金乌元宇助力中国数字文创发展
  8. 学习笔记-基于全局和局部对比自监督学习的高分辨率遥感图像语义分割-day1
  9. 屏幕截图工具 php调用,PicPick 全屏幕截图工具
  10. Web UI - Javascript之DOM Ready