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;
}
}