Unity资源热更新之AssetsBundle

新版本的包要发布,用到的最多的策略就是热更新,那么unity中AssetBundle的资源热更新的方式是怎样的呢?下面就给大家分享AssetBundle资源热更新的方法


简单实现功能

1.菜单栏中添加一个打包的按钮

using System.Collections;  
using System.Collections.Generic;  
using UnityEngine;  
using UnityEditor;  
using System.IO;  
public class CreateAssetsBundle{  
    [MenuItem("MyTool/CreateAssetsBundles")]  
    public static void CreateBundles()  
    {  
        //不能直接打包到Assets目录下,下面的代码提示路径错误  
        //string pathTest = Application.streamingAssetsPath + "/AssetsBundles";  
        //这个是本地路径Assets  
        string path="AssetsBundles";  
        if (!Directory.Exists(path))  
        {  
            Directory.CreateDirectory(path);  
        }  
        //打包 (路径 打包时压缩的方式(使用默认不作处理) 面向的平台)  
            BuildPipeline.BuildAssetBundles(  
            path,  
            BuildAssetBundleOptions.None,  
            BuildTarget.StandaloneOSXIntel64);  
    }  
}  
2.设置要打包的游戏物体

先把游戏物体(Cube /Sphere)拖为预制体


通过单击打包按钮可得如下文件


这是这个包的信息

扫描二维码关注公众号,回复: 5747059 查看本文章

把Hierarchy和预制体中的Cube和Sphere删除,这样可以减小我们工程的大小



3.把这个AssetsBundle放到本地服务器

在Mac搭建服务器

通过WWW来加载打包文件


using System.Collections;  
using System.Collections.Generic;  
using UnityEngine;  
public class CreatAssets : MonoBehaviour {  
    //  // Use this for initialization  
    //  //本地加载  
    //  IEnumerator Start () {  
    //        AssetBundle ab = AssetBundle.LoadFromFile(  
    //            "AssetsBundles/m.assetsbundle"  
    //                        );  
    //        yield return ab;  
    //        Object[] objs = ab.LoadAllAssets();  
    ////        Instantiate(ab.LoadAsset<GameObject>("Cube"));  
    ////        Instantiate(ab.LoadAsset<GameObject>("Sphere"));  
    //       //每使用一次foreach会在堆中产生24bate字节文件,并且无法删除,自能通过GC自动释放  
    //       //使用GC,GC会服务所有的程序,会大大降低cup的性能,因此要减少使用foreach  
    //       foreach(Object item in objs)  
    //       {  
    //           Instantiate(item);  
    //       }  
    //        //false卸载掉所有已经使用     
    //       ab.Unload(false);  
    //}  
    public IEnumerator Start()  
    {  
        AssetBundle ab = null;  
        WWW www = new WWW("http://localhost//AssetsBundles/CubeSphere.assetsbundle");  
        yield return www;  
        if (!string.IsNullOrEmpty(www.error))  
        {  
            Debug.LogError(www.error);  
        }  
        else  
        {  
            ab = www.assetBundle;  
            Object[] objs = ab.LoadAllAssets();  
            foreach (var item in objs)  
            {  
                Instantiate(item);  
            }  
        }  
        ab.Unload(false);  
    }  
}  

猜你喜欢

转载自blog.csdn.net/qq_32225289/article/details/79753218