摘要:本文主要向大家介绍了C#编程之Unity C# 使用JsonUtility读写Json文件,通过具体的内容向大家展示,希望对大家学习C#编程有所帮助。
本文主要向大家介绍了C#编程之Unity C# 使用JsonUtility读写Json文件,通过具体的内容向大家展示,希望对大家学习C#编程有所帮助。
今天,为大家分享一下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
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.然后,我们可以直接运行编辑器看效果!
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标编程语言C#.NET频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号