读取Json文件
读取Json文件
1. 添加后缀
Json 文件 后缀名要加.txt
如 1.json.txt
2. 读文件
TextAsset map = Resources.Load("Map/Config/" + MapId + ".json") as TextAsset;
mapConfigData = JsonUtility.FromJson<MapData>(map.text);
3. 定义了一个类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class MapLayer
{
public int[] data;
public string name;
}
/// <summary>
/// 此类为关卡配置数据结构
/// </summary>
[System.Serializable]
public class MapData
{
public int height;
public int width;
public int hexsidelength;
public bool infinite;
public MapLayer[] layers;
/// <summary>
/// 获取关卡层 id=1
/// </summary>
/// <returns></returns>
public MapLayer GetLevelLayer()
{
return GetLayerByName("level");
}
/// <summary>
/// 获取建筑层 id = 2
/// </summary>
/// <returns></returns>
public MapLayer GetBuildingLayer()
{
return GetLayerByName("building");
}
/// <summary>
/// 获取升级的建筑层 id = 3
/// </summary>
/// <param name="layerName"></param>
/// <returns></returns>
public MapLayer GetUpgradeLayer()
{
return GetLayerByName("upgrade");
}
private MapLayer GetLayerByName(string layerName)
{
for (var i = 0; i < layers.Length; i++)
{
if (layers[i].name == layerName)
{
return layers[i];
}
}
return null;
}
}
4. 获取值
mapConfigData.GetBuildingLayer().data;
mapConfigData.GetBuildingLayer().data;
//int[] LevelArray = mapConfigData.GetLevelLayer().data;
//int[] BuildingArray = mapConfigData.GetBuildingLayer().data;
//MapLayer mapLayer = mapConfigData.GetLevelLayer();