unity不使用协程,加载assetbundle包

公司的项目准备用ab包的形式开发,而加载ab包的功能放在一个没有继承MonoBehaviour的类中,所有在加载ab包的时候,没法用协程来判断ab包是否加载完成,所以我自己用了一种方式来判断;

我用的事异步加载ab包,

AssetBundleCreateRequest asset = AssetBundle.LoadFromFileAsync(path);

  当然还有其他的加载方式,网上有很多大神都对此有很详细的描述,这里我就不在赘述了,我们可以通过委托 asset.completed,当单个资源包加载完成后,要执行的事;

void LoadAssetsBundle()
        {
            m_Path = Application.dataPath;
            //获取运行文件的同级目录
            Directory.SetCurrentDirectory(Directory.GetParent(m_Path).FullName);
            m_Path = Directory.GetCurrentDirectory();
            string assetBundlenPath = ConfigManager.Instance().GetAssetBundlePath();
            m_Path += "/"+ assetBundlenPath;

            m_AssetsNameList = ConfigManager.ReadAssetBundleName();

            string path = m_Path + "/" + m_AssetsNameList[0];

            AssetBundleCreateRequest asset = AssetBundle.LoadFromFileAsync(path);
            asset.completed += AssetBundleLoadcompleted;
           

        }

        private void AssetBundleLoadcompleted(AsyncOperation asset)
        {
            AssetBundleCreateRequest assetBundle = (AssetBundleCreateRequest)asset;
            if (asset == null)
            {
                Debug.Log(m_AssetsNameList[m_Index] + "加载失败");
            }
            else
            {
                Debug.Log(m_AssetsNameList[m_Index] + "加载成功");
                m_AssetBundleList.Add(assetBundle.assetBundle);
            }

            if (m_Index < m_AssetsNameList.Count - 1)
            {
                m_Index++;
                //LoadAsset(m_Index);
                string path = m_Path + "/" + m_AssetsNameList[m_Index];

                if (!File.Exists(path))
                {
                    Debug.Log(m_AssetsNameList[m_Index] + " AssetBundle包文件不存在", LogType.Error);
                    return;
                }
                AssetBundleCreateRequest NextAsset = AssetBundle.LoadFromFileAsync(path);
                NextAsset.completed += AssetBundleLoadcompleted;
                
            }
            else
            {
                Debug.Log(m_AssetsNameList.Count + "个资源包全部加载完成");
                for (int i = 0; i < m_AssetBundleList.Count; i++)
                {
                    Debug.Log(m_AssetBundleList[i].name);
                }
                
            }
        }

  上述代码中有些方法是公司项目中自定义的,需要稍加修改。

新人第一次发帖,如有错误,还望各位大神指出

posted @ 2019-02-23 13:18  贫道徐生  阅读(1182)  评论(0编辑  收藏  举报