由于本人的英语水平过水,因此难免会出现变量名使用拼音命名,英文单词拼错等问题
但我准备了管够的注释,应该没问题吧
实现效果的代码我将其分为两部分
第一部分,我称之为数据仓库对象,负责数据的存入,读取,(如果后面需要加入删除功能也可以直接对其进行拓展)
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using System.IO;//C#系统的包 用于文件读写
public class DetaWarehouseObject : MonoBehaviour
{
//这里是只负责读取 返回一个要求调用的结构体对象
//DatwName是JSON文件保存后的文件名
public static T ReadDATE<T>( string DateName )
{
//JSON数据存放的地址
string DatePath = Application.persistentDataPath + string.Format("/PlayerDate/{0}.json", DateName);
//检查是否有保存的数据
if (!File.Exists(DatePath))
{
// Debug.Log("空数据");
//不存在请求的数据,返回一个空的对象
return default(T);
}
else
{ //数据存在,读取并返回数据
T A = JsonUtility.FromJson<T>( File.ReadAllText(DatePath) );
return A ;
}
}
//这里保存对象 WriteDateType是要保存的结构体对象,DatwName是JSON文件保存后的文件名
public static void writeDATE<T>(T WriteDateType, string DateName)
{
// 检查persistentDataPath 路径下的PlayerDate文件夹是否存在
if (!File.Exists(Application.persistentDataPath + "/PlayerDate"))
{
System.IO.Directory.CreateDirectory(Application.persistentDataPath + "/PlayerDate"); //没有就创建一个
}
string jsonData = JsonUtility.ToJson(WriteDateType);//将结构体转换为JSON字符串
//文件的路径
string filePath = Application.persistentDataPath + string.Format("/PlayerDate/{0}.json", DateName);
//未来可以加入加密功能
File.WriteAllText(filePath, jsonData);//写入文件
Debug.Log("保存结束");
}
}
第二部分 游戏进行时保存数据的对象,使用一个结构体保存,并且在游戏一开始时将会调用数据仓库对象类试图读取已保存的数据
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SetDate : MonoBehaviour
{
public static SitDateStruct SetDateObject;//游戏数据的对象
void Start()
{
//Debug.Log("开始测试"+ SetDateOIbject.GunShootVolume);
//SetDateOIbject.GunShootVolume = 114514;//测试模拟初始化
//DetaWarehouseObject.writeDATE<A>(SetDateOIbject,"SetDate");//存入的测试
SetDateObject = DetaWarehouseObject.ReadDATE<SitDateStruct>("SetDate");//初始化数据库
//Debug.Log("读取测试"+SetDateOIbject.GunShootVolume);
}
[System.Serializable]//序列化的属性
public struct SetDateStruct
{
public float PlayerVolume;
public float BGMVolume;
public float DiRenVolume;
public bool IsNoVolume;
}
}
当想要保存数据时,直接调用数据仓库对象类并传入对应数据的结构体对象和其JSON
文件将使用的名字就行了
大概就这样吧,如果对以上的内容有疑问或发现有错误需要改进的地方,欢迎提问与指正