全局配置文件
步骤
-
在Init脚本中添加全局配置文件组件
Game.Scene.AddComponent<GlobalConfigComponent>();
-
在
GlobalConfigComponent
中通过Awake方法获取配置public void Awake() { Instance = this; //获取配置文件 string configStr = ConfigHelper.GetGlobal(); //转换Json this.GlobalProto = JsonHelper.FromJson<GlobalProto>(configStr); }
-
通过
ConfigHelper
的GetGlobal
方法获取配置文件//加载资源文件夹中的"KV"对象 GameObject config = (GameObject)ResourcesHelper.Load("KV"); //通过对象身上的ReferenceCollector获取配置文件 string configStr = config.Get<TextAsset>("GlobalProto").text; return configStr;
-
ResourcesHelper
用于加载资源文件夹中的对象 -
Get
是GameObject的扩展方法,通过获取对象身上挂载的引用集脚本获取对象public static T Get<T>(this GameObject gameObject, string key) where T : class { try { return gameObject.GetComponent<ReferenceCollector>().Get<T>(key); } catch (Exception e) { throw new Exception($"获取{gameObject.name}的ReferenceCollector key失败, key: {key}", e); } }
-
-
转换Json
通过
JsonHelper
的FromJson
从在方法转换将Json文件转换成GlobalProto
对象//JsonMapper类来源于LitJson插件 T t = JsonMapper.ToObject<T>(str); ISupportInitialize iSupportInitialize = t as ISupportInitialize; if (iSupportInitialize == null) { return t; } iSupportInitialize.EndInit(); return t;
-
最终获取到的配置对象GlobalProto
主要结构如下:
/// <summary>资源服务器地址</summary>
public string AssetBundleServerUrl;
/// <summary>登录服务器地址</summary>
public string Address;
编辑器
using System.IO;
using ETModel;
using UnityEditor;
using UnityEngine;
namespace ETEditor
{
/// <summary>
/// 全局配置文件编辑器
/// </summary>
public class GlobalProtoEditor : EditorWindow
{
//保存路径
const string path = @"./Assets/Res/Config/GlobalProto.txt";
//全局配置文件对象
private GlobalProto globalProto;
//创建对话框
[MenuItem("Tools/全局配置")]
public static void ShowWindow()
{
GetWindow<GlobalProtoEditor>();
}
public void Awake()
{
//检查文件是否存在
if (File.Exists(path))
{
//读取文件并反序列化成对象
this.globalProto = JsonHelper.FromJson<GlobalProto>(File.ReadAllText(path));
}
else
{
//创建文件
this.globalProto = new GlobalProto();
}
}
public void OnGUI()
{
//创建两个输入框,用于保存地址
this.globalProto.AssetBundleServerUrl = EditorGUILayout.TextField("资源路径:", this.globalProto.AssetBundleServerUrl);
this.globalProto.Address = EditorGUILayout.TextField("服务器地址:", this.globalProto.Address);
if (GUILayout.Button("保存"))
{
//序列化成Json文件,并保存到路径
File.WriteAllText(path, JsonHelper.ToJson(this.globalProto));
//刷新Unity资源
AssetDatabase.Refresh();
}
}
}
}