Unity3D 资源热更新之AssetBundle(Unity5.x)基础用法

笔者用的版本是Unity3D 5.5.1

注:AssetBundle 可以包含模型,材质,纹理和场景文件等资源。但是 AssetBundle 不能包含脚本。
 
1.新建Unity3D项目,接着 File -> New Scene 命名 abTest。
2.创建AssetBundles文件夹(放打包资源)、Editor文件夹(放编辑器脚本)、创建Resource文件夹(放预设资源)
Unity3D特殊文件夹参考( http://www.xuanyusong.com/archives/3229

3.在层级视图 (Hierarchy)创建一个Cube,并将Cube拖至Resource文件夹。


4.选中Cube预设,在检视面板(Inspector)下方有个AsetBundle选项,点击右侧选项New资源名称(例如:cube)

5.在Editor创建BuildAssetBundle.cs
using UnityEditor;
using UnityEngine;

namespace Assets
{
    public class BuildAssetBundle
    {
        [MenuItem("Custom/Build Asset Bundle")]
        static void buildAssetBundle()
        {
            string str = Application.dataPath + "/AssetBundles";
            //打包资源路径(参数1:资源保存路径   参数2:未了解    参数3:选择平台,各个平台间不能混用)
            BuildPipeline.BuildAssetBundles(str, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows);
        }
    }
}

通过编辑器打包生成AssetBundle资源

6.接下来就是创建资源加载脚本 LoadAssetBundle.cs
using UnityEngine;
using System.Collections;

public class LoadAssetBundle : MonoBehaviour
{

    private GameObject curObj;
    private string filePath = "";
    private string ObjName = "cube";

    void Start()
    {
        filePath = "file://" + Application.dataPath + "/AssetBundles/" + ObjName;
        StartCoroutine(GetAssetBundleObj(filePath));
    }

    IEnumerator GetAssetBundleObj(string filePath)
    {
        WWW www = new WWW(filePath); //利用www类加载
        yield return www;
        AssetBundle curBundleObj = www.assetBundle; //获得AssetBundle
        AssetBundleRequest obj = curBundleObj.LoadAssetAsync(ObjName, typeof(GameObject)); //异步加载GameObject类型
        yield return obj;
        curObj = Instantiate(obj.asset) as GameObject;
        curObj.name = "cube";
        yield return null;
        curBundleObj.Unload(false);     //卸载所有包含在bundle中的对象,已经加载的才会卸载
        //www.Dispose(); //Unity官方的角度已不再推荐使用Dispose()。官方例子也没有了Dispose()
    }
}
7.将LoadAssetBundle脚本拖至Camera,然后运行程序。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值