通常情况下,我们做展览展示项目所需资源都比较多,项目动不动就超过10G,制作过程中甲方想要外部修改包括视频啊图片啊等资源,而且一般这类项目几乎不会配置服务器,于是乎我们就需要在本地进行外部加载了。
加载方式有好几种,这里主要说的是通过UnityWebRequest加载:
准备某种数据结构
public class TextureConfig_base
{
public string name;
public Texture2D[] textures;
}
协程方法加载资源,加载完成后 注册委托回调
IEnumerator LoadThemeTextures(string dirName, Action<TextureConfig_base> onLoaded)
{
if (Directory.Exists(dirName))
{
string[] paths = Directory.GetFiles(dirName, "*.*", SearchOption.AllDirectories);
List<string> realPathes= new List<string>();
for (int i = 0; i < paths.Length; i++)
{
string extension = Path.GetExtension(paths[i]);
if (extension == ".png" || extension == ".jpg")
{
realPathes.Add(paths[i]);
}
}
List<Texture2D> temp = new List<Texture2D>();
for (int j = 0; j < realPathes.Count; j++)
{
var uri = new Uri(Path.Combine(realPathes[j]));
UnityWebRequest uwr = UnityWebRequest.Get(uri);
DownloadHandlerTexture tex = new DownloadHandlerTexture(true);
uwr.downloadHandler = tex;
yield return uwr.SendWebRequest();
if (uwr.result == UnityWebRequest.Result.ProtocolError || uwr.result == UnityWebRequest.Result.ConnectionError)
{
Debug.LogError(uwr.error);
}
else
{
temp.Add(tex.texture);
}
}
DirectoryInfo info = new DirectoryInfo(dirName);
TextureConfig_base tc = new()
{
name = info.Name,
textures = temp.ToArray()
};
Debug.Log(info.Name + ":加载完成");
onLoaded?.Invoke(tc);
}
}
然后像下面这样调用
string[] jqfiles = Directory.GetDirectories(Path.Combine(DataConfig.jingquDL_Path));
for (int i = 0; i < jqfiles.Length; i++)
{
StartCoroutine(LoadThemeTextures(jqfiles[i], (tc) =>//加载完成回调
{
//自己处理资源数据走向
//DataConfig.jqList.Add(new TextureConfig_jingqu { name=tc.name,textures=tc.textures});
}));
}
到此协程的回调方法展示完成,感谢您的阅读