unity AssetBundle 使用方法2

之前我们已经讲过如何通过AssetBundle 对文件进行打包,现在我们看一下如何将打包的文件添加到我们的unity场景中。

AssetBundle 加载

下载远端服务器的AB

1、通过构建www类进行下载,www类的下载操作最好放在协同程序中异步执行。

    string url = "http://127.0.0.1/GoldenFish.unity3d";
        WWW www = new WWW(url);
        yield return www;
        AssetBundle ab = www.assetBundle;

2、从服务端或者缓存中获取资源
WWW.LoadFromCacheOrDownload(string url, int version)
如果本地缓存中没有该资源,则从服务器下载,否则直接加载本地缓存资源
参数:url 资源所在连接,version 版本(服务端同一资源更新之后,需要更换版本,否则加载内容不变)

string url = "http://127.0.0.1/scenes.scene.assetbundle";
        WWW www = WWW.LoadFromCacheOrDownload(url, 1);
        yield return www;
        AssetBundle ab = www.assetBundle;
        Application.LoadLevel("http-login");//加载场景
加载本地的AB

AssetBundle.CreateFromMemory(byte[] data) 从内存数据流动态创建AB

AssetBundle.CreateFromFile(string path) 从磁盘文件动态创建AB,仅支持非压缩的AB

加载AB中的Assets

AssetBundle.Load() 加载AB中指定名字的Object

AssetBundle.LoadAsync() 异步加载AB中指定名字的Object

AssetBundle.LoadAll() 加载AB中的所有Objects

释放Asset Bundle & Assets

AssetBundle.Unload(false) 仅释放Asset Bundle本身

AssetBundle.Unload(true) 释放Asset Bundle以及从它加载的Assets

Resource.UnloadUnusedAssets() 仅释放没有引用的Assets

示例程序
从服务器下载模型显示在客户端
IEnumerator httpTest3()//从服务器下载模型显示在客户端
    {
        string url = "http://127.0.0.1/GoldenFish.unity3d";

        WWW www = new WWW(url);

        yield return www;
        AssetBundle ab = www.assetBundle;
        Object obj = ab.Load("GoldenFish", typeof(GameObject));
        Instantiate(obj);
        Object[] objs = ab.LoadAll();
        foreach (var item in objs)
        {
            Debug.Log(item.name + "  " + item.GetType());
            if (item.name == "GoldenFish" && item.GetType().ToString() == "UnityEngine.GameObject")
            {
                Instantiate(item);
            }
        }

        Resources.UnloadUnusedAssets();

    }
从服务器下载场景文件
 IEnumerator httpTest4()//从服务器下载场景文件
    {
        string url = "http://127.0.0.1/scenes.scene.assetbundle";
        WWW www = WWW.LoadFromCacheOrDownload(url, 1);
        yield return www;
        AssetBundle ab = www.assetBundle;
        Application.LoadLevel("http-login");//加载场景

    }
从服务器下载依赖文件,被依赖的资源需要下载并加载
IEnumerator httpTest5()//从服务器下载依赖文件
    {
        string url = "http://127.0.0.1/model/texture1.assetbundle";//加载被依赖文件
        WWW www = new WWW(url);
        yield return www;
        AssetBundle ab = www.assetBundle;
        Object[] obj0 = ab.LoadAll();
        //foreach (var item in obj0)
        //{
        //    Debug.Log(item.name + "  " + item.GetType());

        //}
        string url2 = "http://127.0.0.1/model/objB1.assetbundle";//加载文件
        WWW www2 = new WWW(url2);
        yield return www2;
        AssetBundle ab2 = www2.assetBundle;
       //Object[] obj1= ab2.LoadAll();
       //foreach (var item in obj1)
       //{
       //    Debug.Log(item.name + "---" + item.GetType());

       //}
       Object gobj= ab2.Load("Cube2",typeof(GameObject));
       //Debug.Log(gobj.name);
       Instantiate(gobj);
        //Material ma2 = ab2.Load("ma1") as Material;
        //Renderer re = go.transform.GetComponent<Renderer>();
        //re.material = ma2;

    }
将资源打包,同时将信息保存在XML文件中,并通过本机加载显示

打包

 [MenuItem("Tools/打包")]
    public static void ABFolder()
    {
        string folderPath = EditorUtility.OpenFolderPanel("保存路径", "", "");
        Object[] objs = Selection.GetFiltered(typeof(object), SelectionMode.Deep);
        BuildAssetBundleOptions option = BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets | BuildAssetBundleOptions.DeterministicAssetBundle;
        XmlDocument doc = new XmlDocument();
        XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "utf-8", null);
        doc.AppendChild(dec);

        XmlElement root = doc.CreateElement("root");
        doc.AppendChild(root);

        XmlElement scene = doc.CreateElement("scene");
        scene.SetAttribute("name", "level1");
        root.AppendChild(scene);
        Debug.Log("leng=" + objs.Length);
        foreach (var item in objs)
        {
            if (item is GameObject)
            {
                GameObject gob = (GameObject) item;
                XmlElement gamObj = doc.CreateElement("gameObject");
                gamObj.SetAttribute("name", item.name);
                scene.AppendChild(gamObj);


                Object[] data = { item };
                BuildPipeline.BuildAssetBundle(item, data, folderPath + "/" + item.name + ".u3d", option);

                XmlElement pos = doc.CreateElement("position");
                pos.SetAttribute("x", gob.transform.position.x.ToString());
                pos.SetAttribute("y", gob.transform.position.y.ToString());
                pos.SetAttribute("z", gob.transform.position.z.ToString());
                gamObj.AppendChild(pos);

                XmlElement rot = doc.CreateElement("rotation");
                rot.SetAttribute("x", gob.transform.eulerAngles.x.ToString());
                rot.SetAttribute("y", gob.transform.eulerAngles.y.ToString());
                rot.SetAttribute("z", gob.transform.eulerAngles.z.ToString());
                gamObj.AppendChild(rot);

                XmlElement scal = doc.CreateElement("scale");
                scal.SetAttribute("x", gob.transform.localScale.x.ToString());
                scal.SetAttribute("y", gob.transform.localScale.y.ToString());
                scal.SetAttribute("z", gob.transform.localScale.z.ToString());
                gamObj.AppendChild(scal);


            }

        }
        doc.Save(Application.dataPath + "/myXml.xml");
        Debug.Log(Application.dataPath);
    }

加载资源,核心方法是读取XML和加载资源,其他方法与加载打包无关,是项目的其他内容,这里就懒得分离了

using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
public class LoadAssets : MonoBehaviour
{
    public Transform player;
    GameObject currentPrefab;
    Dictionary<string, Vector3[]> inifoDic = new Dictionary<string, Vector3[]>();
    int pos = 0;
    // Use this for initialization
    void Start()
    {
        ReadXml();
    }



    // Update is called once per frame
    void Update()
    {
        if (pos != getPos())
        {
            pos = getPos();
            Destroy(currentPrefab);
            switch (pos)
            {
                case 1:
                    StartCoroutine(CreatAsset("Capsule"));
                    break;
                case 2:
                    StartCoroutine(CreatAsset("Cube"));
                    break;
                case 3:
                    StartCoroutine(CreatAsset("Sphere"));
                    break;
                case 4:
                    StartCoroutine(CreatAsset("Cylinder"));
                    break;
            }

        }

    }

   /// <summary>
   /// 加载资源
   /// </summary>
   /// <param name="name"></param>
   /// <returns></returns>
    IEnumerator CreatAsset(string name)
    {
        string path = "file://" + Application.dataPath + "/StreamingAssets/" + name + ".u3d";
        WWW www = new WWW(path);
        yield return www;
        Object obj = www.assetBundle.Load(name, typeof(GameObject));
        Vector3[] arr;
        inifoDic.TryGetValue(name, out arr);
        if (obj != null)
        {
            currentPrefab = Instantiate(obj) as GameObject;
            currentPrefab.transform.position = arr[0];
            currentPrefab.transform.eulerAngles = arr[1];
            currentPrefab.transform.localScale = arr[2];
        }
        www.assetBundle.Unload(false);
    }

    int getPos()
    {
        if (player.position.x > 0 && player.position.z > 0)
        {
            return 1;
        }
        else if (player.position.x < 0 && player.position.z > 0)
        {
            return 2;
        }
        else if (player.position.x < 0 && player.position.z < 0)
        {
            return 3;
        }
        else if (player.position.x > 0 && player.position.z < 0)
        {
            return 4;
        }

        return 0;
    }

    /// <summary>
    /// 读取XML文件
    /// </summary>
    private void ReadXml()
    {

        XmlDocument xml = new XmlDocument();
        xml.Load(Application.dataPath + "/myXml.xml");
        XmlNodeList objs = xml.SelectSingleNode("root").SelectSingleNode("scene").ChildNodes;
        foreach (XmlElement gob in objs)
        {
            Vector3 pos = Vector3.zero, rot = Vector3.zero, scal = Vector3.one;
            foreach (XmlElement item in gob)
            {
                float x, y, z;

                if (item.Name == "position")
                {
                    x = float.Parse(item.GetAttribute("x"));
                    y = float.Parse(item.GetAttribute("y"));
                    z = float.Parse(item.GetAttribute("z"));
                    pos = new Vector3(x, y, z);



                }
                else if (item.Name == "rotation")
                {
                    x = float.Parse(item.GetAttribute("x"));
                    y = float.Parse(item.GetAttribute("y"));
                    z = float.Parse(item.GetAttribute("z"));
                    rot = new Vector3(x, y, z);
                }
                else if (item.Name == "scale")
                {
                    x = float.Parse(item.GetAttribute("x"));
                    y = float.Parse(item.GetAttribute("y"));
                    z = float.Parse(item.GetAttribute("z"));
                    scal = new Vector3(x, y, z);
                }

            }
            Vector3[] arr = { pos, rot, scal };
            if (!inifoDic.ContainsKey(gob.Name))
            {
                inifoDic.Add(gob.Name, arr);
            }

        }
    }



}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天涯过客TYGK

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值