Unity AssetBundle工作流

一、创建AssetBundle

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

生成的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, 0);
        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;
        }
    }
}

以上便是主要步骤。

原文地址:https://www.cnblogs.com/lurenjiashuo/p/unity3d-assetbundle-workflow.html