将Json文件放置在Resources文件夹下
新建一个UIPanel文件夹,创建一个UIPanelInfo脚本
UIPanelInfo是用作传输数据用的,不继承于MonoBehaviour
using System;
using UnityEngine;
using System.Collections;
[Serializable]
public class UIPanelInfo
{
public UIPanleType panelType;
public string path;
}
创建一个UIManager脚本
此脚本不继承于MonoBehaviour,只做数据传输用
1 using UnityEngine; 2 using System.Collections; 3 using System.Collections.Generic; 4 5 public class UIManager 6 { 7 8 /** 9 * 单例模式的核心: 10 * 1.定义一个静态变量,外部访问,内部构造 11 ** 2.构造方法私有化 12 **/ 13 14 15 //做成单例模式 16 private static UIManager _instance; 17 //外部可以访问到 Instance 18 public static UIManager Instance 19 { 20 //get方法 21 get 22 { 23 //开始运行的时候_instance处于空的状态 24 if (_instance==null) 25 { 26 //此时在这里构造了一个新的UIManager 27 _instance=new UIManager(); 28 } 29 //如果不是第一次运行,说明_instance已经构造了一个UIManager,此时只用返回_instance就可以了 30 return _instance; 31 } 32 } 33 34 private Dictionary<UIPanleType, string> panlePathDict;//存储所有面板prafeb的路径 35 36 //将构造方法私有化 37 private UIManager() 38 { 39 ParseUIPanleTypeJson(); 40 } 41 42 43 44 private void ParseUIPanleTypeJson() 45 { 46 //声明一个字典用于存放数据,方便查找调用 47 panlePathDict =new Dictionary<UIPanleType, string>();//空置字典 48 TextAsset ta= Resources.Load<TextAsset>("UIPanleType");//在Resources文件夹中读取TextAsset类型的“UIPanelType”文件,返回的类型为TextAsset 49 50 //解析Json信息:使用JsonUtility.FromJson方法<生成一个UIPanelInfo的List>然后传递Json信息(ta.text) 51 List< UIPanelInfo> panelInfoList= JsonUtility.FromJson<List<UIPanelInfo>>(ta.text); 52 53 foreach (UIPanelInfo info in panelInfoList)//用UIPanelInfo声明一个新的变量合集info,将panelInfoList的数据在info里遍历一遍 54 { 55 //把遍历后的值保存到空置过后的字典里面 56 panlePathDict.Add(info.panelType,info.path); 57 } 58 59 } 60 }
这样外部就可以通过UIManger.Instance来访问这个脚本的数据