当前位置:   article > 正文

UNITY中ASSET BUNDLE的打包和加载_unity对游戏资源文件夹的打包

unity对游戏资源文件夹的打包

Asset Bundle是Unity引擎提供的一种用于存储资源的文件格式,开发者可以通过Asset Bundle将游戏中所需要的各类资源打包压缩并上传到网络服务器上,另外,在运行时游戏可以从服务器上下载改资源,从而实现资源的动态加载。

下面通过一个工程来讲解Asset Bundle的打包和资源的加载。资源之间没有依赖关系的,Unity官方文档有,比较简单,下面讲资源之间有依赖关系的打包和加载。
打包
1、在场景中新建一个Cube,将其做成一个预设体,再创建一个材质,命名为red,分别将预设体cube和材质red的Asset Bundle名称命名为cube,red,在Unity中Asset Bundle的名称默认为小写。
2、新建一个C#脚本,命名为BuildAssetBundleScript.cs。代码如下:

usingUnityEngine;
usingSystem.Collections;
usingUnityEditor;
publicclassBuildAssetBundleScript:MonoBehaviour
{[MenuItem("AssetBundle/Build")]staticvoidBuildAssetBundle()
{
BuildPipeline.BuildAssetBundles(Application.dataPath+"/AssetBundle");}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

注:通过 BuildPipeline.BuildAssetBundles 方法即可将设置了Asset Bundle的资源全部打包,括号里面是存放Asset Bundle文件的文件夹路径,必须要先在工程中创建出这个文件夹,不然打包的时候会报错。
加载
3、在场景中新建一个空物体,在其上添加一个脚本,命名为LoadAsset.cs。代码如下:

usingUnityEngine;
usingSystem.Collections;
publicclassLoadAsset:MonoBehaviour{
voidStart()
{
StartCoroutine(Load());
}
IEnumeratorLoad()
{
//打包后的资源所在的文件夹
stringassetPath="file://"+Application.dataPath+"/AssetBundle/";
//要加载的目标资源的名称stringrealAssetBundleName="cube";
//加载总的AssetBundle清单文件
WWWwwwManifest=WWW.LoadFromCacheOrDownload(assetPath+"AssetBundle",0);
//等待资源下载完成yieldreturnwwwManifest;
if(wwwManifest.error==null)
{//得到AssetBundle的总清单AssetBundlemanifestBundle=wwwManifest.assetBundle;
//通过清单得到Manifest文件,里面是各个资源之间的依赖关系AssetBundleManifestmanifest=(AssetBundleManifest)manifestBundle.LoadAsset("AssetBundleManifest");
//卸载manifestBundle.Unload(false);
//得到目标资源的依赖关系列表,是依赖关系资源的名字string[]dps=manifest.GetAllDependencies(realAssetBundleName);
//保存所有依赖资源AssetBundle[]abs=newAssetBundle[dps.Length];
for(inti=0;i<dps.Length;i++)
{//各个依赖资源所在路径stringdUrl=assetPath+dps[i];
//根据路径下载资源WWWdwww=WWW.LoadFromCacheOrDownload(dUrl,0);
//等待下载完成yieldreturndwww;abs[i]=dwww.assetBundle;}
//加载目标资源文件WWWwwwCube=WWW.LoadFromCacheOrDownload(assetPath+realAssetBundleName,0);
//等待下载yieldreturnwwwCube;
if(wwwCube.error==null)
{//得到cube资源列表AssetBundlecubeBundle=wwwCube.assetBundle;
//通过资源列表下载资源GameObjectcube=cubeBundle.LoadAsset(realAssetBundleName)asGameObject;Instantiate(cube);
//卸载资源cubeBundle.Unload(false);
}}
}}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/82086
推荐阅读
相关标签
  

闽ICP备14008679号