快速學習——9、讀取解析JSON(三)unity篇
阿新 • • 發佈:2018-12-11
json文字
[
{"id":1,"equipmentName":"無","type":0,"path":"裝備路徑1"},
{"id":2,"equipmentName":"無盡","type":1,"path":"裝備路徑2"},
{"id":3,"equipmentName":"無盡之","type":2,"path":"裝備路徑3"},
{"id":4,"equipmentName":"無盡之刃","type":1,"path":"裝備路徑4"}
]
模板類
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; //裝備基類 [Serializable] public class Equipment { public int id; public string equipmentName; //名稱 public InjuryType type; //型別 public string path; //存放路徑 public Equipment() //不寫可能報錯 { } public Equipment(int id, string equipmentName, InjuryType type, string path) { this.id = id; this.equipmentName = equipmentName; this.type = type; this.path = path; } } //傷害型別 [Serializable] public enum InjuryType { phy,//物理 magic, //魔法 blend//混合 }
讀取json 一個類
儲存所有裝備一個類
讀取
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using LitJson; //讀取json public class JsonTools : MonoBehaviour { public static JsonTools Instance; public TextAsset jsonAsset; //json檔案 private void Awake() { Instance = this; } public Equipment[] ReadJson() { if(jsonAsset == null) //校驗 { Debug.LogWarning("json文字不存在"); return null; } string json = jsonAsset.text; return JsonMapper.ToObject<Equipment[]>(json); } }
儲存
using System.Collections; using System.Collections.Generic; using UnityEngine; //管理裝備 public class EquipmentManager : MonoBehaviour { public Dictionary<int, Equipment> equDict = new Dictionary<int, Equipment>(); public Equipment[] equArray; private void Start() { equArray = JsonTools.Instance.ReadJson(); //新增字典後就可以使用了 foreach (Equipment item in equArray) { if (!equDict.ContainsKey(item.id)) //如果不包含,加入字典 { equDict.Add(item.id, item); Debug.Log(item.id); //輸出測試 } } } }