目录
1.基础存储
unity提供的现成可用的本地存储方式:
PlayerPrefs.SetFloat("size", 1.5f);
PlayerPrefs.SetInt("age", 10);
PlayerPrefs.SetString("name", "David");
2.单个gameObjct数据存储
2.1实体类
using UnityEngine;
public class Entity_fwy
{
public enum_fwy state;
public string name_fwy = "";
public int age;
}
2.2赋值存储
using System.Collections;
using System.Collections.Generic;
using Newtonsoft.Json;
using UnityEngine;
using static Pp_enum;
public class Contr_fwy : MonoBehaviour
{
void Start()
{
Entity_fwy entityFwy = new Entity_fwy();
entityFwy.state = enum_fwy.idle;
entityFwy.name_fwy = "XiaoBai";
entityFwy.age = 18;
//存储
PlayerPrefs.SetString("fwy", JsonConvert.SerializeObject(entityFwy));
//获取
Entity_fwy enFwy = JsonConvert.DeserializeObject<Entity_fwy>(PlayerPrefs.GetString("fwy", ""));
Debug.LogError("cc:" + enFwy.name_fwy);
}
}
3.多个gameObject数据存储
3.1实体类
public class DataSave
{
public string obj_name;
public int obj_id;
public Vector3 obj_pos;
public int obj_scale;
}
3.2list 转json
/// <summary>
/// list 转json
/// </summary>
public static string ToJson<T>(this T list)
{
JsonSerializerSettings settings = new JsonSerializerSettings();
settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
return JsonConvert.SerializeObject(list, settings);
}
3.3存储与解析
[HideInInspector]
public List<DataSave> list_sbHave = new List<DataSave>();
public void dataSave( )
{
//string str = MyUtil.ToJson(list_dataHave_gt);
string str = list_sbHave.ToJson();
Debug.LogError("save:" + str);
PlayerPrefs.SetString("have_sb", str);
}
public void DataGet(string sbType)
{
switch (sbType)
{
case "gt":
string st = PlayerPrefs.GetString("have_sb", "");
JArray ja = (JArray)JsonConvert.DeserializeObject(st);
Debug.LogError("ja:" + ja.Count);
for (int i = 0; i < ja.Count; i++)
{
DataSave ds = new DataSave();
ds.obj_name = "gt";
ds.obj_id = int.Parse(ja[i]["obj_id"].ToString());
JObject jo = JObject.Parse(ja[i]["obj_pos"].ToString());
ds.obj_pos = new Vector3(float.Parse(jo["x"].ToString()), float.Parse(jo["y"].ToString()), -5);
ds.obj_scale = int.Parse(ja[i]["obj_scale"].ToString());
list_sbHave.Add(ds);
}
foreach (DataSave ds in list_sbHave)
{
Debug.LogError(ds.obj_name + "..." + ds.obj_id + "..." + ds.obj_pos.ToString() + "..." + ds.obj_scale.ToString());
}
break;
}
}