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

相关文章

在Android中使用WebView在线查看PDF文件的方法示例

《在Android中使用WebView在线查看PDF文件的方法示例》在Android应用开发中,有时我们需要在客户端展示PDF文件,以便用户可以阅读或交互,:本文主要介绍在Android中使用We... 目录简介:1. WebView组件介绍2. 在androidManifest.XML中添加Interne

Java中字符编码问题的解决方法详解

《Java中字符编码问题的解决方法详解》在日常Java开发中,字符编码问题是一个非常常见却又特别容易踩坑的地方,这篇文章就带你一步一步看清楚字符编码的来龙去脉,并结合可运行的代码,看看如何在Java项... 目录前言背景:为什么会出现编码问题常见场景分析控制台输出乱码文件读写乱码数据库存取乱码解决方案统一使

Java Stream流与使用操作指南

《JavaStream流与使用操作指南》Stream不是数据结构,而是一种高级的数据处理工具,允许你以声明式的方式处理数据集合,类似于SQL语句操作数据库,本文给大家介绍JavaStream流与使用... 目录一、什么是stream流二、创建stream流1.单列集合创建stream流2.双列集合创建str

PHP轻松处理千万行数据的方法详解

《PHP轻松处理千万行数据的方法详解》说到处理大数据集,PHP通常不是第一个想到的语言,但如果你曾经需要处理数百万行数据而不让服务器崩溃或内存耗尽,你就会知道PHP用对了工具有多强大,下面小编就... 目录问题的本质php 中的数据流处理:为什么必不可少生成器:内存高效的迭代方式流量控制:避免系统过载一次性

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

Spring Security简介、使用与最佳实践

《SpringSecurity简介、使用与最佳实践》SpringSecurity是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架,本文给大家介绍SpringSec... 目录一、如何理解 Spring Security?—— 核心思想二、如何在 Java 项目中使用?——

springboot中使用okhttp3的小结

《springboot中使用okhttp3的小结》OkHttp3是一个JavaHTTP客户端,可以处理各种请求类型,比如GET、POST、PUT等,并且支持高效的HTTP连接池、请求和响应缓存、以及异... 在 Spring Boot 项目中使用 OkHttp3 进行 HTTP 请求是一个高效且流行的方式。

python获取指定名字的程序的文件路径的两种方法

《python获取指定名字的程序的文件路径的两种方法》本文主要介绍了python获取指定名字的程序的文件路径的两种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要... 最近在做项目,需要用到给定一个程序名字就可以自动获取到这个程序在Windows系统下的绝对路径,以下

Java使用Javassist动态生成HelloWorld类

《Java使用Javassist动态生成HelloWorld类》Javassist是一个非常强大的字节码操作和定义库,它允许开发者在运行时创建新的类或者修改现有的类,本文将简单介绍如何使用Javass... 目录1. Javassist简介2. 环境准备3. 动态生成HelloWorld类3.1 创建CtC

JavaScript中的高级调试方法全攻略指南

《JavaScript中的高级调试方法全攻略指南》什么是高级JavaScript调试技巧,它比console.log有何优势,如何使用断点调试定位问题,通过本文,我们将深入解答这些问题,带您从理论到实... 目录观点与案例结合观点1观点2观点3观点4观点5高级调试技巧详解实战案例断点调试:定位变量错误性能分