实现Unity下加载Json格式文本。
a. 准备1个文本格式为utf-8的txt文件,以及读取文件的LoadJSONFile.cs脚本,作为测试的JsonVO.cs脚本,在网上下载LitJson插件并导入Unity;
b.脚本代码如下:
usingUnityEngine;
usingSystem.Collections;
usingSystem.IO;
usingLitJson;
publicclass LoadJSONFile : MonoBehaviour
{
private JsonVO[] _jsonStr;
void Start()
{
LoadJSON();
if(_jsonStr != null &&_jsonStr.Length > 0)
{
foreach(JsonVO jo in _jsonStr)
{
Debug.Log(jo.HeroName + "," + jo.Profession + ", " + jo.HeroLevel);
}
}
}
private void LoadJSON()
{
//设置文件位置,根据自己的需要进行设置
string filePath = Application.dataPath+ "/LoadFileStudy/Resources/studyJSON.txt";
try
{
string[] _string =File.ReadAllLines(filePath);
_jsonStr = newJsonVO[_string.Length];
for (int m = 0; m <_string.Length; m++)
{
_jsonStr[m] =JsonMapper.ToObject<JsonVO>(_string[m]);
}
}
catch (IOException e)
{
Debug.Log("加载出现问题,问题描述:"+ e);
}
}
}
c. 将脚本LoadJSONFile添加至摄像机上。
d. 脚本 JsonVO.cs代码如下:
usingUnityEngine;
usingSystem.Collections;
publicclass JsonVO : MonoBehaviour
{
public string HeroName;
public string Profession;
public string HeroLevel;
public string HeroIcon;
public string HeroHP;
public string HeroMP;
public string HeroDefense;
public string NormalAttack;
public string MagicAttack;
}
e. 脚本JsonVO不需要挂在任何物体上。
f. 运行后Console输出如图1所示:
图1
g. studyJSON.txt文本下的内容如图2所示: