1.编写脚本,该脚本并未继承MonoBehaviour,所以不用挂载到物体上即可使用
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using System.IO;
public class WRJson
{
[MenuItem("Tools/Write")]//增加菜单栏按钮
static void WriteJson()//写入数据
{
//Application.dataPath路径只对PC端有效,如果JsonData文件夹中没有JsonText文件,会自动创建
string path = Application.dataPath + "/JsonData/JsonText.json";
Human human = new Human();
People people = new People();
people.name = "张三";
people.age = 17;
people.hob = "跳舞";
human.obj.Add(people);
People people2 = new People();
people.name = "李四";
people2.age = 15;
people2.hob = "跳高";
human2.obj.Add(people2);
string str = JsonUtility.ToJson(human);
File.WriteAllText(path, str);//写入Json文件
AssetDatabase.Refresh();//刷新Json文件中的数据
}
[MenuItem("Tools/Read")]//增加菜单栏按钮
static void ReadJson()//读取数据
{
string path = Application.dataPath + "/JsonData/JsonData.json";//PC端项目的根目录
string str = File.ReadAllText(path);//读取Json文件
Human data = JsonUtility.FromJson<Human>(str);
for (int i = 0; i < data.obj.Count; i++)
{
Debug.Log(data.obj[i].name);
Debug.Log(data.obj[i].age);
Debug.Log(data.obj[i].hob);
}
}
}
[Serializable]//序列化
public class Human
{
public List<People> obj = new List<People>();
}
[Serializable]//序列化
public class People
{
public string name;
public int age;
public string hob;
}
2.保存脚本代码后,回到unity可以看到多了Tools菜单栏,以及Write和Read菜单选项
3.点击Write后,可以看到JsonData文件夹中多出了一个JsonText的Json文件,而且写入了内容
4.点击Read,可以看到Console控制台打印了JsonText中的文件信息(也可以不使用脚本代码自己编写Json文件,然后读取Json数据到Unity中)
结语:合抱之木,生于毫末;九层之台,起于累土;千里之行,始于足下。