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文件的內容:

大致的讀取與寫入功能已經寫好,詳細的內容與具體的實現就不羅嗦了!

      


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM