多语言展示
当前在线:700今日阅读:183今日分享:45

Unity 入门教程 之 快速学会数据Json格式化

Unity 入门教程 之 快速学会数据Json格式化。Json数据格式化,把一般数据转化为Json 结构格式保存,本节通过Unity自带的Json来实现数据Json,具体如下
工具/原料
1

Unity

2

JsonUtility

一、基本概念
1

JsonUtility:Utility functions for working with JSON data.

2

JsonUtility.ToJson:Generate a JSON representation of the public fields of an object.Internally, this method uses the Unity serializer; therefore the object you pass in must be supported by the serializer: it must be a MonoBehaviour, ScriptableObject, or plain class/struct with the Serializable attribute applied. The types of fields that you want to be included must be supported by the serializer; unsupported fields will be ignored, as will private fields, static fields, and fields with the NonSerialized attribute applied.

3

注意事项提醒:在使用JsonUtility.ToJson(),数据记得“Serializable”,例如:[Serializable]public class PersonInfo {    public string name;    public int age;}

二、入门教程 之 快速学会数据Json格式化
1

打开Unity,新建一个空工程,然后Unity界面如下图

2

在工程中新建一个脚本,脚本可以命名为“JsonUtilityTest”,选中脚本,双击脚本或者右键“Open C# Project”,具体如下图

3

在打开的“JsonUtilityTest”脚本上进行代码编辑,首先定义两个数据类,用来便于储存数据信息,并把“Serializable”数据类,具体代码及代码说明如下图

4

在打开的“JsonUtilityTest”脚本上进行代码编辑,然后通过上面定义好的数据类用来设置信息,并且通过JsonUtility.ToJson()把数据Json化,具体代码及代码说明如下图

5

具体脚本内容如下:using System;using UnityEngine;[Serializable]public class PersonInfo {    public string name;    public int age;}[Serializable]public class Person {    public PersonInfo[] persons;}public class JsonUtilityTest : MonoBehaviour { // Use this for initialization void Start () {        PersonInfo person1 = new PersonInfo();        person1.name = '鹿晗';        person1.age = 27;        PersonInfo person2 = new PersonInfo();        person2.name = '王俊凯';        person2.age = 18;        PersonInfo[] persons = new PersonInfo[] {person1, person2 };        Person person = new Person();        person.persons = persons;        string personsInfo = JsonUtility.ToJson(person);        print('人员信息:\r\n ' +personsInfo); } }

6

脚本编译正确后,回到Unity界面,在场景中新建一个“GameObject”,然后把脚本“JsonUtilityTest ”赋给“GameObject”,具体如下图

7

运行场景,即可看到数据以Json格式打印在控制台Console上,具体如下图

8

到此,《Unity 入门教程 之 快速学会数据Json格式化》讲解结束,谢谢

注意事项

若帮到您,还请帮忙投票以帮助到更多的人;若有疑问,请留言

推荐信息