AssetBundle的制作与加载

发表于2018-03-22
评论0 1.2k浏览
AssetBundle实现了资源与服务分离,方便大家做热更新,下面就分别给大家介绍下如何制作和加载AssetBundle。

【AssetBundle简介】

设计原理:一个资源可以分到多个包里;多个资源可以打进一个包里
可以实时从任意位置 加载资源包
运行时加载,将资源打成包,自己控制整个资源的管理,加载效率稍微差
要自己控制整个打包和资源的管理,包括资源的引用计数
对资源的管理更加精确,可以在线更新某个资源。

【制作AssetBundle】

这里在编辑器扩展了一个按钮,点击按钮,开始将资源打包成AssetBundle
编辑器扩展简单介绍
using UnityEngine;  
using System.Collections;  
using System.Collections.Generic;  
using UnityEditor;  
public class BuildBundle  
{  
    [MenuItem("Tools/MakeBundle")]  
    public static void MakeBundle()  
    {  
        List<AssetBundleBuild> builds = new List<AssetBundleBuild>();  
        AssetBundleBuild bundle = new AssetBundleBuild();  
        bundle.assetBundleName = "build.unity3d";  
        //需要将该工程目录的路径填写完整,包括文件后缀名  
        //可以往数组里继续添加需要打包成AssetBundle的资源  
        bundle.assetNames = new string[] { "Assets/03_Bundle/Prefabs/Cube.prefab", "Assets/03_Bundle/Prefabs/Sphere.prefab" };  
        builds.Add(bundle);  
        //参数一:打包到的路径(路径必须存在)参数二:需要打包的AssetBundle数组(这里只打包了一个AssetBundle)  
        BuildPipeline.BuildAssetBundles("Assets/03_Bundle/Bundle", builds.ToArray());  
    }  
}

【加载AssetBundle】

由于AssetBundle是加载效率稍差
故这里简单介绍使用协程异步加载AssetBundle
using UnityEngine;  
using System.Collections;  
public class LoadBundle : MonoBehaviour   
{  
    // Use this for initialization  
    void Start ()   
    {  
        StartCoroutine(LoadMyBundle());  
    }  
    // Update is called once per frame  
    void Update ()   
    {  
    }  
    IEnumerator LoadMyBundle()  
    {  
        //加载本地文件  
        //也可以从网络服务器上加载bundle  
        WWW www = new WWW("file://D:/Unity3d/unity3d object/TextObject_2/Assets/03_Bundle/Bundle/build.unity3d");  
        yield return www;  
        //从bundle上加载asset文件  
        AssetBundle bundle = www.assetBundle;  
        //异步加载asset  
        AssetBundleRequest req = bundle.LoadAssetAsync("Assets/03_Bundle/Prefabs/Cube.prefab",typeof(GameObject));  
        yield return req;  
        GameObject obj = req.asset as GameObject;  
        GameObject.Instantiate(obj);  
        //安全处置www  
        www.Dispose();  
    }  
}  

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引