Unity 资源热更之AssetBundle

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/leonardo_Davinci/article/details/78503966

通过阅读:http://blog.csdn.net/y1196645376/article/details/52556938

简单实现功能

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)拖为预制体


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


这是这个包的信息

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

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

在Mac搭建服务器 http://blog.csdn.net/snowrain1108/article/details/50072057

通过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/leonardo_Davinci/article/details/78503966