👨💻个人主页:@元宇宙-秩沅
👨💻 hallo 欢迎 点赞👍 收藏⭐ 留言📝 加关注✅!
👨💻 本文由 秩沅 原创
👨💻 收录于专栏:Unity基础实战
⭐🅰️⭐
文章目录
⭐前言⭐
🎶()持久数据文件夹
- 先获取文件夹的位置
- 1.存储字符串到指定路径文件中
- 2.在指定路径文件中读取字符串
🎶()JsonUtlity进行序列化
- 现实作用:
1.将对象序列化成Json格式
2.将Json格式反序列化为对象
- 引用 using System.IO
🪶0. jsonUtilty的注意点(缺点)
😶🌫️注意:
1.float序列化时看起来会有一些误差
2.被包裹的自定义类需要加上序列化特性[System.Serializable]
3.想要序列化私有变量 需要加上特性[SerializeField]
4.JsonUtility不支持字典
5.JsonUtlity存储null对象不会是null 而是默认值的数据,
比如空int 会变成0
6.JsonUtility无法直接反序列化读取数据集合"[]",需要用一个对象包裹它
7.文本编码格式需要时UTF-8 不然无法加载
🪶1.将对象序列化成字符串(Json格式)
-
string jsonStr = JsonUtility.ToJson( dataGame );
// DataGame 是类对象
-
File.WriteAllText(Application.persistentDataPath + “/text1.json”, jsonStr);
//将序列化后的字符串数据存在文件夹中
🪶2.将Json反序列化成对象
-
jsonStr = File.ReadAllText(Application.persistentDataPath + “/text1.json”);
//读取文件中的字符串
-
DataGame dataGame = JsonUtility.FromJson(jsonStr);
//使用Json字符串内容 转换成类对象
-
代码
jsonStr = File.ReadAllText(Application.persistentDataPath + "/text1.json");
DataGame dataGame = JsonUtility.FromJson<DataGame >(jsonStr);
🪶3.练习(将序列化和反序列化变成方法调用)
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;
[System.Serializable]
public class Item
{
public int id;
public int num;
public Item( int ID,int NUM)
{
id = ID;
num = NUM;
}
}
public class BossInfo
{
public string name;
public int attack;
public int defence;
public float moveSpeed;
public double roundSpeed;
public Item weapon;
public List<int> listInt;
public List<Item> itemList;
public Dictionary<int, Item> itemDic1;
public Dictionary<string, Item> itemDic2;
[SerializeField ]
private int self = 2 ;
[SerializeField]
protected int pro = 3;
//序列化
public void serilized(BossInfo obj)
{
if(obj!=null )
{
string onjInfo = JsonUtility.ToJson(obj);
File.WriteAllText(Application.persistentDataPath + ("/BossInfo.json"), onjInfo);
}
}
//反序列化
public BossInfo RevSerilized(string path)
{
if (path != null)
{
string objInfo = File.ReadAllText(Application.persistentDataPath +"/"+ path);
return JsonUtility.FromJson<BossInfo>(objInfo);
}
else return null;
}
}
public class text : MonoBehaviour
{
private void Start()
{
BossInfo boss = new BossInfo();
boss.name = "鸭嘴兽";
boss.attack = 100;
boss.defence = 20;
boss.moveSpeed = 50;
boss.roundSpeed = 30;
boss.weapon = new Item(001, 10);
boss.listInt = new List<int>() { 1, 2, 3, 4 };
boss.itemList = new List<Item>() { new Item(002, 10), new Item(003, 10) };
boss.itemDic1 = new Dictionary<int, Item>() { { 1, new Item(002, 10) }, { 2, new Item(003, 10) } };
boss.itemDic2 = new Dictionary<string, Item>() { { "鸭子1", new Item(003, 10) }, { "鸭子2", new Item(004, 10) } };
boss.serilized(boss); //JsonUyility 不支持字典
print(Application.persistentDataPath);
boss.RevSerilized("BossInfo.json");
}
}
⭐🅰️⭐
你们的点赞👍 收藏⭐ 留言📝 关注✅是我持续创作,输出优质内容的最大动力!、