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

最近在作项目的时候想给工程里加一个读取外部资源包的功能,由于是个展现类的项目,若是要增长新的产品只须要将资源打包,经过加载资源包就能够作到不用从新build就能够更新。这也是热更新中的一个环节ios

 

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

        建立C#脚本取名为CreateAssetBundle此为打包脚本,在Editor下执行便可,贴上代码windows

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)接下来将须要打包的资源整理好作成预制ui

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

      

     文件类型设置为unity3d便可3d

3)下来就能够打包了code

        在菜单栏中选择Tools->Buildblog

         

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

     

 

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

将这两个文件放入须要加载资源的工程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打包资源及加载资源就完成了

相关文章
相关标签/搜索