您的位置:首页 > 移动开发 > Unity3D

AssetBundle的制作与加载

2017-01-02 19:19 169 查看
【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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  assetbundle unity3d