为了熟悉一下资源加载的API,做了一个加载图片的小demo,实现了4种加载图片方式,并且把同步与异步做了区分。
使用unity开发游戏的过程中,资源的加载一直都是需要重点关注的。unity一共提供了5种资源加载的方式,分别是Resources(只能加载Resources目录中的资源),AssetBundle(只能加载AB资源,当前设备允许访问的路径都可以),WWW(可以加载任意处资源,包括项目外资源(如远程服务器)),AssetDatabase(只能加载Assets目录下的资源,但只能用于Editor),UnityWebRequest(可以加载任意处资源,是WWW的升级版本)。关于加载的的具体方法建议直接看Unity的API,讲解的比较明白,这里提一下同步与异步加载的意思与优缺点:
同步:并不是按字面意思的同时或一起,而是指协同步调,协助、相互配合。是按先后顺序执行在发出一个功能调用时,在没有得到返回结果之前一直在等待,不会继续往下执行。异步:刚好和同步相反,也就是在发出一个功能调用时,不管没有没得到结果,都继续往下执行,异步加载至少有一帧的延迟。
同步的优点:管理方便,资源准备好可以及时返回。缺点:没有异步快。
异步的优点:速度快与主线程无关。缺点:调用比较麻烦,最好的做法是使用回调。
在UnityWebRequest和WWW的使用过程中使用了回调,为了方便以后自己使用,贴一下代码:
首先是定义一个资源加载的接口:
public interface IResourcesLoadingMode {
void ResourcesLoading<T>(T t,string path, bool IsAsync) where T:UnityEngine.Object;
void ResourcesUnLoading<T>(T t)where T:UnityEngine.Object;
}
然后是资源加载的基类:
public class ResourcesLoadingMode : IResourcesLoadingMode
{
public Image Img;
public MonoBehaviour MB;
public virtual void ResourcesLoading<T>(T t,string path, bool IsAsync) where T:UnityEngine.Object
{
throw new NotImplementedException();
}
public virtual void ResourcesUnLoading<T>(T t) where T : UnityEngine.Object
{
throw new NotImplementedException();
}
}
这里的monoBehaviour是因为整个资源加载器没有继承MonoBehaviour,在异步加载的时候可以把上层控制层的MonoBehavior拿过来,以便可以调用协程实现异步加载。这里直接用回调了。
Resouces方式:
public override void ResourcesLoading<T>(T t,string path, bool IsAsync)
{
if (IsAsync == false)
{
T load = Resources.Load<T>(path);
t = load;
Debug.Log("===="+path+"====");
if (t.GetType() == Img.sprite.GetType())
{
Img.sprite = t as Sprite;
Resources.UnloadAsset(t);
}
}
else
{
T load = Resources.LoadAsync<T>(path).asset as T;
t = load;
if (t.GetType() == Img.