版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35030499/article/details/82804999
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); //输出测试
}
}
}
}