赞
踩
JsonUtility是Unity官方的一个解析Json的API,下面是我定义的Json文件,记录了项目中的panle预制件名字和与其所在的路径。
{
"infoList":
[
{
"panelTypeString": "MainMenu",
"path": "UIPanel/MainMenuPanel"
},
{
"panelTypeString": "Task",
"path": "UIPanel/TaskPanel"
},
{
"panelTypeString": "Knapsack",
"path": "UIPanel/KnapsackPanel"
},
{
"panelTypeString": "Skill",
"path": "UIPanel/SkillPanel"
},
{
"panelTypeString": "Battle",
"path": "UIPanel/BattlePanel"
},
{
"panelTypeString": "System",
"path": "UIPanel/SystemPanel"
},
{
"panelTypeString": "KnapsackPop",
"path": "UIPanel/KnapsackPopPanel"
}
]
}
为了从json文件里面获取到相关的信息,需要做以下准备,代码如下:
using UnityEngine;
using System;
/// <summary>
/// panel 信息类
/// </summary>
/// 注意这里需要加这个可序列化属性 [Serializable],不然解析会报错
[Serializable]
public class PanelInfo:ISerializationCallbackReceiver {
[NonSerialized]
public UIPanelType panelType;
public string panelTypeString;
//{
// get { return panelType.ToString(); }
// set
// {
// UIPanelType type=(UIPanelType) System.Enum.Parse(typeof(UIPanelType), value);
// panelType = type;
// }
//}
public string path;
public void OnBeforeSerialize()
{
}
//反序列化=>从文本信息到对象
public void OnAfterDeserialize()
{
UIPanelType type = (UIPanelType)System.Enum.Parse(typeof(UIPanelType),panelTypeString);
panelType = type;
}
}
/// <summary>
/// 对应json文件里面的数组
/// </summary>
/// [Serializable] 属性不可缺,不然会报错
[Serializable]
class UIPanelTypeJson
{
public List<PanelInfo> infoList;
}
/// <summary>
/// 解析json文件过程
/// </summary>
private void UIPanelPathParson()
{
panelPathDict = new Dictionary<UIPanelType, string>();
TextAsset uiPanelType = Resources.Load<TextAsset>("UIPanelType");
UIPanelTypeJson panelTypeJson= JsonUtility.FromJson<UIPanelTypeJson>(uiPanelType.text);
foreach (PanelInfo panelInfo in panelTypeJson.infoList)
{
Debug.Log(panelInfo.path);
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。