【Unity-学习-006】Unity 使用 JsonDotNet 插件,实现数据本地化

Unity商城里有一个免费插件 JsonDotNet,可以实现以json文件的形式实现数据本地化。

这个插件支持自定义class的存储,SaveData<T> 和 ReadData<T> 需要把要存储的类型一块传过去。

 

以下是完整代码。


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Newtonsoft.Json;
using System.IO;

public class DataHandle
{

    StreamWriter writer;
    StreamReader reader;
    string filePath = Application.persistentDataPath; //安卓路径 是 android/data/xxx.xxx.xxx/file  


    //把所有的数据写入文本中
    public void WriteIntoTxt(string message, string fileName)
    {
        FileInfo file = new FileInfo(filePath + "/" + fileName);
        if (!file.Exists)
        {
            writer = file.CreateText();
        }
        else
        {
            file.Delete();
            writer = file.CreateText();
        }
        writer.WriteLine(message);
        writer.Flush();
        writer.Dispose();
        writer.Close();
    }


    //读取存储到列表中
    public string ReadOutTxt(string fileName)
    {
        FileInfo file = new FileInfo(filePath + "/" + fileName);
        if (!file.Exists)
        {
            writer = file.CreateText();
            writer.Flush();
            writer.Dispose();
            writer.Close();

            return "nil"; //null 文件不存在并切已经刚刚创建了一个
        }


        reader = new StreamReader(filePath + "/" + fileName);
        string text;
        string str = "";
        while ((text = reader.ReadLine()) != null)
        {
            str += text;
        }

        reader.Dispose();
        reader.Close();

        return str;
    }

    //存储数据
    public void SaveData<T>(T tempT, string fileName)
    {
        string str = JsonConvert.SerializeObject(tempT);
        WriteIntoTxt(str, fileName);
    }

    public void DeletData(string fileName)
    {
        FileInfo file = new FileInfo(filePath + "/" + fileName);
        if (file.Exists)
        {
            file.Delete();
        }
    }


    //读取数据
    public T ReadData<T>(string fileName)
    {
        T tempT;
        string str = ReadOutTxt(fileName);
        if (str != "nil")
        {
            tempT = JsonConvert.DeserializeObject<T>(str);
        }
        else
        {
            tempT = default;
        }
        return tempT;
    }

}

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ThursdayGame

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值