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