码迷,mamicode.com
首页 > 编程语言 > 详细

Unity -JsonUtility的使用

时间:2017-03-17 19:38:46      阅读:1065      评论:0      收藏:0      [点我收藏+]

标签:void   编辑器   unity3d   serial   UI   sha   com   nbsp   json 解析   

今天,为大家分享一下unity上的Json序列化,应该一说到这个词语,我们肯定会觉得,这应该是很常用的一个功能点;诚然,我们保存数据的时候,也许会用到json序列化,所以,我们有必要快速了解一下它的简单用法。技术分享【小白篇】
  
     官方文档:https://docs.unity3d.com/Manual/JSONSerialization.html

     1.首先,我们直接新建unity项目,然后新建一个JsonUtilityBehaviour.cs 组件测试类;
        
         技术分享 
        

       JsonUtilityBehaviour.cs 代码如下:

 

 1 using UnityEngine;
 2 using System;
 3  
 4 public class JsonUtilityBehaviour : MonoBehaviour {
 5  
 6     People _p;
 7     string _toJsonStr;
 8     People _fromP;
 9  
10     void OnGUI()
11     {
12          
13         if (GUI.Button(new Rect(100, 100, 100, 50), "Json 序列化"))
14         {
15             NewPeople();
16             _toJsonStr = JsonUtility.ToJson(_p);
17         }
18         GUI.Label(new Rect(100,150,200,50), _toJsonStr);
19         
20         if (GUI.Button(new Rect(100, 200, 100, 50), "Json 解析"))
21         {
22             _fromP = JsonUtility.FromJson<People>(_toJsonStr);
23         }
24         GUI.Label(new Rect(100, 250, 200, 50), GetFromJsonStr());
25     }
26  
27     void NewPeople()
28     {
29         _p = new People();
30         _p.Name = "HappyKing";
31         _p.Age = 18;
32     }
33  
34     string  GetFromJsonStr()
35     {
36         string str = "";
37         if (_fromP != null)
38             str = "我的名字叫" + _fromP.Name + ",今年" + _fromP.Age + "了!";
39         return str;
40     }
41      
42 }
43  
44 [Serializable]
45 public class People
46 {
47     public string Name;
48     public int Age;
49 }

  2.然后,我们可以直接运行编辑器看效果!

       技术分享 

       技术分享 

Unity -JsonUtility的使用

标签:void   编辑器   unity3d   serial   UI   sha   com   nbsp   json 解析   

原文地址:http://www.cnblogs.com/AdvancePikachu/p/6567623.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!