unity AssetBundle 使用方法2

2024-06-09 14:48

本文主要是介绍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 initializationvoid Start(){ReadXml();}// Update is called once per framevoid 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);}}}}

这篇关于unity AssetBundle 使用方法2的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1045482

相关文章

C++使用栈实现括号匹配的代码详解

《C++使用栈实现括号匹配的代码详解》在编程中,括号匹配是一个常见问题,尤其是在处理数学表达式、编译器解析等任务时,栈是一种非常适合处理此类问题的数据结构,能够精确地管理括号的匹配问题,本文将通过C+... 目录引言问题描述代码讲解代码解析栈的状态表示测试总结引言在编程中,括号匹配是一个常见问题,尤其是在

Nginx设置连接超时并进行测试的方法步骤

《Nginx设置连接超时并进行测试的方法步骤》在高并发场景下,如果客户端与服务器的连接长时间未响应,会占用大量的系统资源,影响其他正常请求的处理效率,为了解决这个问题,可以通过设置Nginx的连接... 目录设置连接超时目的操作步骤测试连接超时测试方法:总结:设置连接超时目的设置客户端与服务器之间的连接

Java中String字符串使用避坑指南

《Java中String字符串使用避坑指南》Java中的String字符串是我们日常编程中用得最多的类之一,看似简单的String使用,却隐藏着不少“坑”,如果不注意,可能会导致性能问题、意外的错误容... 目录8个避坑点如下:1. 字符串的不可变性:每次修改都创建新对象2. 使用 == 比较字符串,陷阱满

Java判断多个时间段是否重合的方法小结

《Java判断多个时间段是否重合的方法小结》这篇文章主要为大家详细介绍了Java中判断多个时间段是否重合的方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录判断多个时间段是否有间隔判断时间段集合是否与某时间段重合判断多个时间段是否有间隔实体类内容public class D

Python使用国内镜像加速pip安装的方法讲解

《Python使用国内镜像加速pip安装的方法讲解》在Python开发中,pip是一个非常重要的工具,用于安装和管理Python的第三方库,然而,在国内使用pip安装依赖时,往往会因为网络问题而导致速... 目录一、pip 工具简介1. 什么是 pip?2. 什么是 -i 参数?二、国内镜像源的选择三、如何

使用C++实现链表元素的反转

《使用C++实现链表元素的反转》反转链表是链表操作中一个经典的问题,也是面试中常见的考题,本文将从思路到实现一步步地讲解如何实现链表的反转,帮助初学者理解这一操作,我们将使用C++代码演示具体实现,同... 目录问题定义思路分析代码实现带头节点的链表代码讲解其他实现方式时间和空间复杂度分析总结问题定义给定

IDEA编译报错“java: 常量字符串过长”的原因及解决方法

《IDEA编译报错“java:常量字符串过长”的原因及解决方法》今天在开发过程中,由于尝试将一个文件的Base64字符串设置为常量,结果导致IDEA编译的时候出现了如下报错java:常量字符串过长,... 目录一、问题描述二、问题原因2.1 理论角度2.2 源码角度三、解决方案解决方案①:StringBui

Linux使用nload监控网络流量的方法

《Linux使用nload监控网络流量的方法》Linux中的nload命令是一个用于实时监控网络流量的工具,它提供了传入和传出流量的可视化表示,帮助用户一目了然地了解网络活动,本文给大家介绍了Linu... 目录简介安装示例用法基础用法指定网络接口限制显示特定流量类型指定刷新率设置流量速率的显示单位监控多个

Java覆盖第三方jar包中的某一个类的实现方法

《Java覆盖第三方jar包中的某一个类的实现方法》在我们日常的开发中,经常需要使用第三方的jar包,有时候我们会发现第三方的jar包中的某一个类有问题,或者我们需要定制化修改其中的逻辑,那么应该如何... 目录一、需求描述二、示例描述三、操作步骤四、验证结果五、实现原理一、需求描述需求描述如下:需要在

JavaScript中的reduce方法执行过程、使用场景及进阶用法

《JavaScript中的reduce方法执行过程、使用场景及进阶用法》:本文主要介绍JavaScript中的reduce方法执行过程、使用场景及进阶用法的相关资料,reduce是JavaScri... 目录1. 什么是reduce2. reduce语法2.1 语法2.2 参数说明3. reduce执行过程