Unity C# 使用JsonUtility读写Json文件

 [Serializable]
 public class InputData 
 {
      public InputDataEntry[] data;
 }
  
 [Serializable]
 public class InputDataEntry
 {
     public string name;
     public int age;
 }

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 }

猜你喜欢

转载自blog.csdn.net/qq_21743659/article/details/131064307