这个配置管理器的功能是在编辑器模式在从Resources目录下加载配置,打出的包要从AssetBundle里面加载,如果各位不需要的话,直接在DownloadConfigs里面注释掉LoadLocalConfig之外的所有行就好了,这个应该很简单,我就不多说了。
RegistAllLoadFuncs()方法里面注册的是一个传string参数的方法,这个应该也很明显,具体的实现每个项目应该都有自己的一套,我们的项目都是csv格式,大家自己实现就好了。
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UConfigManager : MonoBehaviour
{
private static UConfigManager mInstance;
public static UConfigManager Instance
{
get
{
if (mInstance == null)
{
GameObject go = new GameObject("UConfigManager");
DontDestroyOnLoad(go);
mInstance = go.AddComponent<UConfigManager>();
}
return mInstance;
}
}
public void Init() { }
private Dictionary<string, Action<string>> dExcelLoaders = new Dictionary<string, Action<string>>();
private void RegistLoadFunc(string sExcelName, Action<string> func)
{
dExcelLoaders.Add(sExcelName, func);
}
private void RegistAllLoadFuncs()
{
/*RegistLoadFunc("Levels", ULoaderLevel.Instance.LoadData);
RegistLoadFunc("Localization", ULoaderLocalization.Instance.LoadData);*/
}
void Awake()
{
mInstance = this;
RegistAllLoadFuncs();
DownloadConfigs();
}
private void DownloadConfigs()
{
#if UNITY_EDITOR
LoadLocalConfig();
#else
StartCoroutine(DoDownload());
#endif
}
public static string DownLoadConfigPath = "http://192.168.1.100/configs/configs.assetbundle";
private IEnumerator DoDownload()
{
var www = new WWW(DownLoadConfigPath);
yield return www;
if (string.IsNullOrEmpty(www.error))
{
var ab = www.assetBundle;
LoadAssetBundle(ab);
ab.Unload(true);
}
else
{
Debug.Log("加载远端配置失败,正在加载本地配置。");
LoadLocalConfig();
}
www.Dispose();
}
private void LoadAssetBundle(AssetBundle ab)
{
Debug.Log("下载远端配置成功,正在加载远端配置。");
foreach (var s in dExcelLoaders.Keys)
{
var text = ab.LoadAsset(s) as TextAsset;
if (text == null)
{
Debug.Log("Cannot load " + s + " from asset bundle");
continue;
}
dExcelLoaders[s](text.text);
}
}
private void LoadLocalConfig()
{
foreach (var s in dExcelLoaders.Keys)
{
var text = Resources.Load<TextAsset>("Configs/" + s);
if (text == null)
{
Debug.Log("Cannot load " + s + " from local");
continue;
}
dExcelLoaders[s](text.text);
}
}
}
剩下的就是在合适的时机,调用
UConfigManager.Instance.Init();