随笔-Unity关于利用AssetBundle打包资源与加载资源

最近在做项目的时候想给工程里加一个读取外部资源包的功能,因为是个展示类的项目,如果要增加新的产品只需要将资源打包,通过加载资源包就可以做到不用重新build就可以更新。这也是热更新中的一个环节。

1)首先在Asset根目录下创建EditorStreamingAssets文件夹

        创建C#脚本取名为CreateAssetBundle此为打包脚本,在Editor下执行即可,贴上代码。

public class AutoCreateAssetBundle : Editor
{
    const string path = "Assets/StreamingAssets/";
    [MenuItem("Tools/Build")]
    public static void BuildAssetBundle()
    {
        string outPath = path;
        if (!Directory.Exists(outPath))
        {
            Directory.CreateDirectory(outPath);
        }
        BuildPipeline.BuildAssetBundles(outPath, BuildAssetBundleOptions.None, EditorUserBuildSettings.activeBuildTarget);
        AssetDatabase.Refresh();
    }
}

2)接下来将需要打包的资源整理好做成预制。

        在Project视图中选中需要打包的资源的预制体,设置AssetBundle的名字和文件类型。

         

         文件类型设置为unity3d即可。

3)下来就可以打包了

         在菜单栏中选择Tools->Build

        

4)等待打包完成就会在StreamingAssets目录下生成两个文件

    

至此打包工作就完成了,下面是加载部分

将这两个文件放入需要加载资源的工程StreamingAssets的目录

不过多赘述了,直接上代码。

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

    public class LoadBuildAsset : MonoBehaviour
    {
        private string path;

        private void Awake()
        {

            path =
#if UNITY_STANDALONE_WIN || UNITY_EDITOR
                    "file://" + Application.dataPath + "/StreamingAssets/";  //windows和web平台
#elif UNITY_IPHONE
                    Application.dataPath + "/Raw/";                          //ios平台
#elif UNITY_ANDROID
                    "jar:file://" + Application.dataPath + "!/assets/";      //andriod平台
#else
                     string.Empty;
#endif
            buildName = "boxandui.unity3d";

            StartCoroutine(LoadMainGameObject(path + buildName));
        }

        /// <summary>
        /// 获取资源
        /// </summary>
        /// <param name="_path"></param>
        /// <returns></returns>
        private IEnumerator LoadMainGameObject(string _path)
        {
            using (WWW asset = new WWW(_path))
            {
                yield return asset;
                AssetBundle ab = asset.assetBundle;
                UnityEngine.Object[] objs = ab.LoadAllAssets();
                GameObject objCache;
                foreach (var obj in objs)
                {
                    objCache = Instantiate(obj) as GameObject;
                }
                yield return new WaitForSeconds(3);
            }
        }
    }

 这里需要注意的就是不同的平台StreamingAssets的路径是不同的

 至此,利用AssetBundle打包资源及加载资源就完成了

 

猜你喜欢

转载自blog.csdn.net/zhangchong5522/article/details/119387738