使用Unity提供的JsonUtility 简单封装了一个将数据以json格式存储到本地,方便数据读写的案例;
一共三个脚本:
MyJsonRW : 提供SaveJsonData和LoadWithJson,实现数据与json的转换和读写;
TestData : 测试数据类,列举了部分常用的简单数据类型(不过有坑,后面会说);
MyJsonExample : 例子实践,随便弄的UI;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.IO;
public class MyJsonRW
{
public static void SaveJsonData<T>(string path, T data)
{
if (string.IsNullOrEmpty(path))
{
Debug.LogError("存储路径不存在");
return;
}
string json = JsonUtility.ToJson(data, true);
File.WriteAllText(path, json);
Debug.Log("json存储完成,路径:" + path);
}
public static T LoadWithJson<T>(string path)
{
if (string.IsNullOrEmpty(path))
{
Debug.LogError