unity3d 动态加载资源Resources.Load和AssetBundle

来源:互联网 发布:淘宝宝贝被别人复制了 编辑:程序博客网 时间:2024/05/18 20:52

unity3d Resources.Load动态加载资源



1.首先总结下unity有哪几种资源类型

     unity资源的类型:

    -a) Unity内置的常用asset,                   fbx\jpg...

  - b) textasset:                                         txt、binary等,对应了它的TextAsset类,可以直接读入文本或者二进制byte

   -c) scriptable object                             它是序列化的Object实例,例如把一个Object实例保存成scriptable object,读入进来后就直接在内存中变成那个实例

    - d) asset bundle                                  它是一个资源压缩包,里面包含了一堆资源


通常我们自定义的文件类型可以通过textasset 或scriptable object 来存储,区别在于前者是一个字节或文本流,后者要对应于程序中一个定义了的类型,textasset 还通常用于资源的加密。


2.动态load资源的几种途径:

   -通过Resources模块,调用它的load函数:可以直接load并返回某个类型的Object,前提是要把这个资源放在Resource命名的文件夹下,Unity不关有没有场景引用,都会将其全部打入到安装包中。

        -通过bundle的形式:即将资源打成 asset bundle 放在服务器或本地磁盘,然后使用WWW模块get 下来,然后从这个bundle中load某个object。

        -通过AssetDatabase.loadasset :这种方式只在editor范围内有效,游戏运行时没有这个函数,它通常是在开发中调试用的


       Resources的方式需要把所有资源全部打入安装包,这对游戏的分包发布(微端)和版本升级(patch)是不利的,所以unity推荐的方式是不用它,都用bundle的方式替代,把资源达成几个小的bundle,用哪个就load哪个,这样还能分包发布和patch,但是在开发过程中,不可能没更新一个资源就打一次bundle,所以editor环境下可以使用AssetDatabase来模拟,这通常需要我们封装一个dynamic resource的loader模块,在不同的环境下做不同实现。


3.动态资源的存放

  有时我需要存放一些自己的文件在磁盘上,例如我想把几个bundle放在初始的安装里, unity有一个streaming asset的概念,用于提供存储接口的访问。我们需要在编辑器建立一个StreamingAssets名字的文件夹,把需要我们放在客户磁盘上的动态文件放在这个文件夹下面,这样安装后,这些文件会放在用户磁盘的指定位置,这个位置可以通过Application.streamingAssetsPath来得到。


  初步整理并且学习unity3d资源加载方法,预计用时两天完成入门学习Unity3d常用两种加载资源方案:Resources.LoadAssetBundle

Resources.Load就是从一个缺省打进程序包里的AssetBundle里加载资源而一般AssetBundle文件需要你自己创建,运行时动态加载,

可以指定路径和来源的。其实场景里所有静态的对象也有这么一个加载过程,只是Unity后台替你自动完成

一:Resources.Load:使用这种方式加载资源,首先需要下Asset目录下创建一个名为Resources的文件夹,这个命名是U3D规定的方式,然后把资源文件放进去,

当然也可以在Resources中再创建子文件夹,当然在代码加载时需要添加相应的资源路径,下面是一个简demo,两个预设,CubeSphere

其中Cube放在Resource中的Prebs中,而Sphere放在Resources跟目录下,下面分别实现Resources.Load资源的加载

 

复制代码
using UnityEngine;using System.Collections;public class LoadResDemo : MonoBehaviour {    private string cubePath = "Prebs/MyCubePreb";    private string spherePath = "MySpherePreb";    void Start () {        //把资源加载到内存中        Object  cubePreb = Resources.Load(cubePath, typeof(GameObject));        //用加载得到的资源对象,实例化游戏对象,实现游戏物体的动态加载        GameObject cube = Instantiate(cubePreb) as GameObject;        //以下同理实现Sphere的动态实例化        //把资源加载到内存中        Object spherePreb = Resources.Load(spherePath, typeof(GameObject));        //用加载得到的资源对象,实例化游戏对象,实现游戏物体的动态加载        GameObject sphere = Instantiate(spherePreb) as GameObject;    }        void Update () {        }}
复制代码

  将上面的脚本附加到某个游戏对象上,在运行游戏时就可以看到场景中动态创建的上面的游戏对象了

上面是第一种使用Resources.Load()的方式动态加载游戏对象的,然而在项目中更长用的却是第二种使用AssetBundle的方式动态加载游戏对象。


二、使用AssetBundle打包预设或者场景可以将与其相关的所有资源打包,这样很好地解决资源的依赖问题,使得我们可以方便的加载GameObject

首先需要打包资源:

复制代码
using UnityEngine;using System.Collections;using UnityEditor;using System.IO;public class AesstBundleTest : MonoBehaviour {    [MenuItem("Custom Bundle/Create Bundel Main")]    public static void creatBundleMain()    {        //获取选择的对象的路径        Object[] os = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);        bool isExist = Directory.Exists(Application.dataPath + "/StreamingAssets");        if (!isExist)        {            Directory.CreateDirectory(Application.dataPath + "/StreamingAssets");        }        foreach (Object o in os)        {            string sourcePath = AssetDatabase.GetAssetPath(o);            string targetPath = Application.dataPath + "/StreamingAssets/" + o.name + ".assetbundle";            if (BuildPipeline.BuildAssetBundle(o, null, targetPath, BuildAssetBundleOptions.CollectDependencies))            {                print("create bundle cuccess!");            }            else            {                print("failure happen");            }            AssetDatabase.Refresh();        }    }    [MenuItem("Custom Bundle/Create Bundle All")]    public static void CreateBundleAll()    {        bool isExist = Directory.Exists(Application.dataPath + "/StreamingAssets");        if (!isExist)        {            Directory.CreateDirectory(Application.dataPath + "/StreamingAssets");        }        Object[] os = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);        if (os == null || os.Length == 0)        {            return;        }        string targetPath = Application.dataPath + "/StreamingAssets/" + "All.assetbundle";        if (BuildPipeline.BuildAssetBundle(null, os, targetPath, BuildAssetBundleOptions.CollectDependencies))        {            print("create bundle all cuccess");        }        else        {            print("failure happen");        }        AssetDatabase.Refresh();    }}
复制代码

把上面的代码放在Editor中,在菜单栏中就可以看见自定的菜单项,选中需要打包的预设,就可以把对应的预设打包并输出到StreamAssets中了

然后是动态加载资源:

复制代码
using UnityEngine;using System.Collections;public class LoadBundleTest : MonoBehaviour {    //不同平台下StreamingAssets的路径是不同的,这里需要注意一下。    public static readonly string PathURL =    #if UNITY_ANDROID        "jar:file://" + Application.dataPath + "!/assets/";    #elif UNITY_IPHONE        Application.dataPath + "/Raw/";    #elif UNITY_STANDALONE_WIN || UNITY_EDITOR    "file://" + Application.dataPath + "/StreamingAssets/";    #else        string.Empty;    #endif        // Update is called once per frame    void Update () {        }    void OnGUI()    {        if (GUILayout.Button("Load Bundle Main"))        {            string path_shpere = PathURL + "MySpherePreb.assetbundle";            StartCoroutine(loadBundleMain(path_shpere));            string path_cube = PathURL + "MyCubePreb.assetbundle";            StartCoroutine(loadBundleMain(path_cube));            print(path_cube);        }        if (GUILayout.Button("Load Bundle All"))        {            StartCoroutine(loadBundleAll(PathURL + "All.assetbundle"));        }    }    private IEnumerator loadBundleMain(string path)    {        WWW bundle = new WWW(path);      //  yield return bundle;         Instantiate(bundle.assetBundle.mainAsset);         bundle.assetBundle.Unload(false);         yield return 1;    }    private IEnumerator loadBundleAll(string path)    {        WWW bundle = new WWW(path);        yield return bundle;        Instantiate(bundle.assetBundle.Load("MyCubePreb"));        Instantiate(bundle.assetBundle.Load("MySpherePreb"));        yield return 1;    }}
复制代码

 

0 0
原创粉丝点击