Unity C# 使用JsonUtility读写Json文件

本文原创,转载请注明出处:http://www.cnblogs.com/AdvancePikachu/p/7146731.html 

 

今天,为大家分享一下unity上的Json序列化,应该一说到这个词语,我们肯定会觉得,这应该是很常用的一个功能点;诚然,我们保存数据的时候,也许会用到json序列化,所以,我们有必要快速了解一下它的简单用法。

     1.首先,我们直接新建unity项目,然后新建一个InputData.cs 数据结构类;

代码如下:

 1 [Serializable]
 2 public class InputData 
 3 {
 4     public InputDataEntry[] data;
 5 }
 6 
 7 [Serializable] 8 public class InputDataEntry 9 { 10 public string name; 11 public int age; 12 }

2.然后建一个AppManager.cs的组件类  

         

 AppManager.cs 代码如下:

 

 1 public class AppManager : MonoBehaviour {
 2 
 3     InputData _inputDate = new InputData ();
 4 
 5     InputData inputDate 
 6     {
 7         get
 8         { 
 9             return _inputDate; 10  } 11 set 12  { 13 _inputDate = value; 14  } 15  } 16 17 string path; 18 bool truename; 19 20 void Start () 21  { 22 path = Application.dataPath + "/Resources/inputdate.json"; 23 24 if (LoadFromFile () != null) 25 inputDate = LoadFromFile (); 26  } 27 28  InputData LoadFromFile() 29  { 30 if (!File.Exists (path)) 31 return null; 32 33 StreamReader sr = new StreamReader (path); 34 35 if (sr == null) 36 return null; 37 38 string json = sr.ReadToEnd (); 39 40 if (json.Length > 0) 41 return JsonUtility.FromJson<InputData> (json); 42 43 return null; 44  } 45 46 47 void OnApplicationQuit () 48  { 49 string json = JsonUtility.ToJson (inputDate, true); 50  File.WriteAllText (path, json, Encoding.UTF8); 51  } 52 53 public void RangNumber() 54  { 55 InputDataEntry[] ide = new InputDataEntry[1]; 56 ide [0] = new InputDataEntry (); 57 ide [0].age = Random.Range (18, 26); 58 59 if (truename) 60 truename = false; 61 else 62 truename = true; 63 64 ide [0].name = truename ? "AdvancePikachu" : "进击的皮卡丘"; 65 inputDate.data = ide; 66 67 Debug.Log ("age :" + ide [0].age + "\n name :" + ide [0].name); 68  } 69 }

 

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

       

 

如下的json文件的内容:

大致的读取与写入功能已经写好,详细的内容与具体的实现就不罗嗦了!

      

转载于:https://www.cnblogs.com/AdvancePikachu/p/7146731.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值