Unity AssetBundle工作流

时间:2023-03-09 16:32:57
Unity AssetBundle工作流

一、创建AssetBundle

1、在资源的Inspector视图下有一个AssetBundle的UI,第一个选项表示AssetBundle名称,第二个用于设置AssetBundle Variant,主要用于在不同版本资源的使用和动态替换AssetBundle。

Unity AssetBundle工作流

2、在Unity的Assets文件夹下创建Editor文件夹,创建一个C#脚本,用于创建AssetBundle,代码如下:

using UnityEngine;
using UnityEditor; public class TestAssetBundles : MonoBehaviour { [MenuItem("Custom Editor/Build AssetBunldes")]
static void CreateAssetBundlesMain()
{
BuildPipeline.BuildAssetBundles("Assets/StreamingAssets", BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows64);
}
}

注:这里的MenuItem是用于在Unity编辑器的菜单上添加一个菜单项。输出路径为Assets下的StreamingAssets文件夹(确保存在)。

3、选择菜单栏中的Custom Editor->Build AssetBundles命令,即可在输出路径中看到打包的AssetBundle。

Unity AssetBundle工作流

生成的AssetBundle:

Unity AssetBundle工作流

这里的test.assetbundle即是要上传到服务器上下载的AssetBundle文件(如果有依赖关系,还要上传test.assetbundle.manifest文件)。

二、下载AssetBundle并加载

using System.Collections;
using UnityEngine; public class loadasset : MonoBehaviour { void Start () {
StartCoroutine("loadAssetBundle");
} IEnumerator loadAssetBundle()
{
string assetBundlePath = "file://" + Application.dataPath + "/StreamingAssets/test.assetbundle";
Debug.Log(assetBundlePath);
WWW www = WWW.LoadFromCacheOrDownload(assetBundlePath, );
yield return www;
if (www.error == null)
{
AssetBundle myLoadAssetBundle = www.assetBundle; AssetBundleRequest request = myLoadAssetBundle.LoadAssetAsync("park", typeof (GameObject));
yield return request; GameObject obj = request.asset as GameObject;
Instantiate(obj); myLoadAssetBundle.Unload(false);
} else
{
Debug.Log(www.error);
yield return null;
}
}
}

以上便是主要步骤。