管理与加载指定AB的资源。

一、直接上代码

/***
 *
 *   Title: "AssetBundle简单框架"项目
 *          框架主流程: 
 *          第1层: AB(AssetBundle)资源加载类
 *          
 *
 *   Description:
 *          功能: 
 *              1: 管理与加载指定AB的资源。
 *              2: 加载具有“缓存功能”的资源,带选用参数。
 *              3: 卸载、释放AB资源。
 *              4: 查看当前AB资源。
 *
 *   Author: Liuguozhu
 *
 *   Date: 2017.10
 *
 *   Modify:  
 *
 */
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace ABFW
{
    public class AssetLoader : System.IDisposable
    {
        //当前Assetbundle 
        private AssetBundle _CurrentAssetBundle;
        //缓存容器集合
        private Hashtable _Ht;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="abObj">给定WWW加载的AssetBundle 实例</param>
        public AssetLoader(AssetBundle abObj)
        {
            if (abObj != null)
            {
                _CurrentAssetBundle = abObj;
                _Ht = new Hashtable();
            }
            else {
                Debug.Log(GetType()+"/ 构造函数 AssetBundle()/ 参数 abObj==null! ,请检查");
            }
        }


        /// <summary>
        /// 加载当前包中指定的资源
        /// </summary>
        /// <param name="assetName">资源的名称</param>
        /// <param name="isCache">是否开启缓存</param>
        /// <returns></returns>
        public UnityEngine.Object LoadAsset(string assetName,bool isCache=false)
        {
            return LoadResource<UnityEngine.Object>(assetName, isCache);
        }

        /// <summary>
        /// 加载当前AB包的资源,带缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="assetName">资源的名称</param>
        /// <param name="isCache">是否需要缓存处理</param>
        /// <returns></returns>
        private T LoadResource<T>(string assetName,bool isCache) where T : UnityEngine.Object
        {
            //是否缓存集合已经存在
            if (_Ht.Contains(assetName))
            {
                return _Ht[assetName] as T;
            }

            //正式加载
            T tmpTResource=_CurrentAssetBundle.LoadAsset<T>(assetName);
            //加入缓存集合
            if (tmpTResource != null && isCache)
            {
                _Ht.Add(assetName, tmpTResource);
            } else if (tmpTResource==null)
            {
                Debug.LogError(GetType()+ "/LoadResource<T>()/参数 tmpTResources==null, 请检查!");
            }

            return tmpTResource;
        }


        /// <summary>
        /// 卸载指定的资源
        /// </summary>
        /// <param name="asset">资源名称</param>
        /// <returns></returns>
        public bool UnLoadAsset(UnityEngine.Object asset)
        {
            if(asset!=null)
            {
                Resources.UnloadAsset(asset);
                return true;
            }
            Debug.LogError(GetType()+ "/UnLoadAsset()/参数 asset==null ,请检查!");
            return false;
        }

        /// <summary>
        /// 释放当前AssetBundle内存镜像资源
        /// </summary>
        public void Dispose()
        {
            _CurrentAssetBundle.Unload(false);
        }

        /// <summary>
        /// 释放当前AssetBundle内存镜像资源,且释放内存资源。
        /// </summary>
        public void DisposeALL()
        {
            _CurrentAssetBundle.Unload(true);
        }

        /// <summary>
        /// 查询当前AssetBundle中包含的所有资源名称。
        /// </summary>
        /// <returns></returns>
        public string[] RetriveAllAssetName()
        {
            return _CurrentAssetBundle.GetAllAssetNames();
        }
    }
}

二、WWW 加载AssetBundle

 

/***
 *
 *   Title: "AssetBundle简单框架"项目
 *          框架主流程: 
 *          第2层: WWW 加载AssetBundel 
 *
 *   Description:
 *          功能: 
 *
 *   Author: Liuguozhu
 *
 *   Date: 2017.10
 *
 *   Modify:  
 *
 */
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace ABFW
{
    public class SingleABLoader: System.IDisposable
    {
        //引用类: 资源加载类
        private AssetLoader _AssetLoader;
        //委托:
        private DelLoadComplete _LoadCompleteHandle;
        //AssetBundle 名称
        private string _ABName;
        //AssetBundle 下载路径
        private string _ABDownLoadPath;

        //构造函数
        public SingleABLoader(string abName,DelLoadComplete loadComplete)
        {
            _AssetLoader = null;
            _ABName = abName;
            //委托初始化
            _LoadCompleteHandle = loadComplete;
            //AB包下载路径(初始化)
            _ABDownLoadPath = PathTools.GetWWWPath() + "/" + _ABName;            
        }

        //加载AssetBundle 资源包
        public IEnumerator LoadAssetBundle()
        {
            using (WWW www=new WWW(_ABDownLoadPath))
            {
                yield return www;
                //WWW下载AB包完成
                if (www.progress>=1)
                {
                    //获取AssetBundle的实例
                    AssetBundle abObj = www.assetBundle;
                    if (abObj!=null)
                    {
                        //实例化引用类
                        _AssetLoader = new AssetLoader(abObj);
                        //AssetBundle 下载完毕,调用委托
                        if (_LoadCompleteHandle!=null)
                        {
                            _LoadCompleteHandle(_ABName);
                        }

                    }
                    else {
                        Debug.LogError(GetType()+ "/LoadAssetBundle()/WWW 下载出错,请检查! AssetBundle URL: "+ _ABDownLoadPath+" 错误信息: "+www.error);
                    }
                }
            }//using_end            
        }

        /// <summary>
        /// 加载(AB包内)资源
        /// </summary>
        /// <param name="assetName"></param>
        /// <param name="isCache"></param>
        /// <returns></returns>
        public UnityEngine.Object LoadAsset(string assetName,bool isCache)
        {
            if (_AssetLoader!=null)
            {
                return _AssetLoader.LoadAsset(assetName,isCache);
            }
            Debug.LogError(GetType()+ "/LoadAsset()/ 参数_AssetLoader==null  ,请检查!");
            return null;
        }

        /// <summary>
        /// 卸载(AB包中)资源
        /// </summary>
        /// <param name="asset"></param>
        public void UnLoadAsset(UnityEngine.Object asset)
        {
            if (_AssetLoader != null)
            {
                _AssetLoader.UnLoadAsset(asset);
            }
            else {
                Debug.LogError(GetType()+ "/UnLoadAsset()/参数 _AssetLoader==Null , 请检查!");
            }
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            if (_AssetLoader != null)
            {
                _AssetLoader.Dispose();
                _AssetLoader = null;
            }
            else
            {
                Debug.LogError(GetType() + "/Dispose()/参数 _AssetLoader==Null , 请检查!");
            }
        }

        /// <summary>
        /// 释放当前AssetBundle资源包,且卸载所有资源
        /// </summary>
        public void DisposeALL()
        {
            if (_AssetLoader != null)
            {
                _AssetLoader.DisposeALL();
                _AssetLoader = null;
            }
            else
            {
                Debug.LogError(GetType() + "/DisposeALL()/参数 _AssetLoader==Null , 请检查!");
            }
        }

        /// <summary>
        /// 查询当前AssetBundle包中所有的资源
        /// </summary>
        /// <returns></returns>
        public string[] RetrivalAllAssetName()
        {
            if (_AssetLoader != null)
            {
                return _AssetLoader.RetriveAllAssetName();
            }
            Debug.LogError(GetType() + "/RetrivalAllAssetName()/参数 _AssetLoader==Null , 请检查!");
            return null;
        }
    }
}

三、路径工具

/***
 *
 *   Title: "AssetBundle简单框架"项目
 *          路径工具类
 *
 *   Description:
 *          功能: 
 *          包含本框架中所有的路径常量、路径方法
 *
 *   Author: Liuguozhu
 *
 *   Date: 2017.10
 *
 *   Modify:  
 *
 */
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace ABFW
{
    public class PathTools
    {
        /* 路径常量 */
        public const string AB_RESOURCES = "AB_Res";

        /* 路径方法 */
        /// <summary>
        /// 得到AB资源的输入目录
        /// </summary>
        /// <returns></returns>
        public static string GetABResourcesPath()
        {
            return Application.dataPath + "/"+ AB_RESOURCES;
        }

        /// <summary>
        /// 获取AB输出路径
        /// 算法:
        ///     1: 平台(PC/移动端)路径。
        ///     2: 平台的名称
        /// </summary>
        public static string GetABOutPath()
        {
            return GetPlatformPath() + "/" + GetPlatformName();
        }

        /// <summary>
        /// 获取平台的路径
        /// </summary>
        /// <returns></returns>
        private static string GetPlatformPath()
        {
            string strReturnPlatformPath = string.Empty;


            switch (Application.platform)
            {
                case RuntimePlatform.WindowsPlayer:
                case RuntimePlatform.WindowsEditor:
                    strReturnPlatformPath = Application.streamingAssetsPath;
                    break;
                case RuntimePlatform.IPhonePlayer:
                case RuntimePlatform.Android:
                    strReturnPlatformPath = Application.persistentDataPath;
                    break;      
                default:
                    break;
            }

            return strReturnPlatformPath;
        }

        /// <summary>
        /// 获取平台的名称
        /// </summary>
        /// <returns></returns>
        public static string GetPlatformName()
        {
            string strReturnPlatformName = string.Empty;

            switch (Application.platform)
            {
                case RuntimePlatform.WindowsPlayer:
                case RuntimePlatform.WindowsEditor:
                    strReturnPlatformName = "Windows";
                    break;
                case RuntimePlatform.IPhonePlayer:
                    strReturnPlatformName = "Iphone";
                    break;
                case RuntimePlatform.Android:
                    strReturnPlatformName = "Android";
                    break;
                default:
                    break;
            }

            return strReturnPlatformName;
        }


        /// <summary>
        /// 获取WWW协议下载(AB包)路径
        /// </summary>
        /// <returns></returns>
        public static string GetWWWPath()
        {
            //返回路径字符串
            string strReturnWWWPath = string.Empty;

            switch (Application.platform)
            {
                //Windows 主平台
                case RuntimePlatform.WindowsPlayer:
                case RuntimePlatform.WindowsEditor:
                    strReturnWWWPath = "file://" + GetABOutPath();
                    break;
                //Android 平台
                case RuntimePlatform.Android:
                    strReturnWWWPath = "jar:file://" + GetABOutPath();
                    break;
                //IPhone平台
                case RuntimePlatform.IPhonePlayer:
                    strReturnWWWPath = GetABOutPath()+"/Raw/";
                    break;
                default:
                    break;
            }

            return strReturnWWWPath;
        }
        
    }
}

四、常量工具

/***
 *
 *   Title: "AssetBundle简单框架"项目
 *          工具类:     
 *
 *   Description:
 *          功能: 
 *             1: 本框架项目所有的常量
 *             2: 所有的委托定义。
 *             3: 枚举定义。
 *             4: 常量定义。
 *
 *   Author: Liuguozhu
 *
 *   Date: 2017.10
 *
 *   Modify:  
 *
 */
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace ABFW
{
    /* 委托定义区 */
    public delegate void DelLoadComplete(string abName);


    /* 枚举类型定义 */

    public class ABDefine
    {
        /* 框架常量 */
        public static string ASSETBUNDLE_MANIFEST = "AssetBundleManifest";
        
    }
}


五、测试

/***
 *
 *   Title: "AssetBundle简单框架"项目
 *           框架内部验证测试
 *           
 *   Description:
 *          功能: 
 *             专门验证 “SingABLoader”类
 *
 *   Author: Liuguozhu
 *
 *   Date: 2017.10
 *
 *   Modify:  
 *
 */
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

namespace ABFW
{
    public class TestClass_SingABLoader:MonoBehaviour
    {
        //引用类
        private SingleABLoader _LoadObj = null;
        /*  依赖AB包名称  */
        private string _ABDependName1 = "scence_1/textures.ab"; //贴图AB包
        private string _ABDependName2 = "scence_1/materials.ab";//材质AB包
        //AB包名称
        private string _ABName1 = "scence_1/prefabs.ab";
        //AB包中资源名称
        private string _AssetName1 = "TestCubePrefab.prefab";//Capsule.prefab


        #region 简单(无依赖包)预设的加载
        //private void Start()
        //{
        //    _LoadObj = new SingleABLoader(_ABName1, LoadComplete);
        //    //加载AB包
        //    StartCoroutine(_LoadObj.LoadAssetBundle());
        //}

        / <summary>
        / 回调函数(一定条件下自动执行)
        / </summary>
        / <param name="abName"></param>
        //private void LoadComplete(string abName)
        //{
        //    //加载AB包中的资源
        //    UnityEngine.Object tmpObj=_LoadObj.LoadAsset(_AssetName1,false);
        //    //克隆对象
        //    Instantiate(tmpObj);
        //}

        #endregion

        private void Start()
        {
            SingleABLoader _LoadDependObj = new SingleABLoader(_ABDependName1, LoadDependComplete1);
            //加载AB依赖包
            StartCoroutine(_LoadDependObj.LoadAssetBundle());
        }

        //依赖回调函数1
        private void LoadDependComplete1(string abName)
        {
            Debug.Log("依赖包1(贴图包)加载完毕,加载依赖包2(材质包)");
            SingleABLoader _LoadDependObj2 = new SingleABLoader(_ABDependName2, LoadDependComplete2);
            //加载AB依赖包
            StartCoroutine(_LoadDependObj2.LoadAssetBundle());
        }

        //依赖回调函数2
        private void LoadDependComplete2(string abName)
        {
            Debug.Log("依赖包2(材质包)加载完毕,开始正式加载预设包");
            _LoadObj = new SingleABLoader(_ABName1, LoadComplete);
            //加载AB依赖包
            StartCoroutine(_LoadObj.LoadAssetBundle());
        }

        /// <summary>
        /// 回调函数(一定条件下自动执行)
        /// </summary>
        /// <param name="abName"></param>
        private void LoadComplete(string abName)
        {
            //加载AB包中的资源
            UnityEngine.Object tmpObj = _LoadObj.LoadAsset(_AssetName1, false);
            //克隆对象
            Instantiate(tmpObj);

            /*  查询包中的资源*/
            string[] strArray = _LoadObj.RetrivalAllAssetName();
            foreach (string str in strArray)
            {
                Debug.Log(str);
            }
        }

        private void Update()
        {
            if (Input.GetKeyDown(KeyCode.A))
            {
                Debug.Log("释放镜像内存资源,与内存资源");
                //_LoadObj.Dispose();//释放镜像内存资源
                _LoadObj.DisposeALL();//释放镜像内存资源,与内存资源
            }
        }

    }
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值