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

相关文章

Spring LDAP目录服务的使用示例

《SpringLDAP目录服务的使用示例》本文主要介绍了SpringLDAP目录服务的使用示例... 目录引言一、Spring LDAP基础二、LdapTemplate详解三、LDAP对象映射四、基本LDAP操作4.1 查询操作4.2 添加操作4.3 修改操作4.4 删除操作五、认证与授权六、高级特性与最佳

Qt spdlog日志模块的使用详解

《Qtspdlog日志模块的使用详解》在Qt应用程序开发中,良好的日志系统至关重要,本文将介绍如何使用spdlog1.5.0创建满足以下要求的日志系统,感兴趣的朋友一起看看吧... 目录版本摘要例子logmanager.cpp文件main.cpp文件版本spdlog版本:1.5.0采用1.5.0版本主要

Java中使用Hutool进行AES加密解密的方法举例

《Java中使用Hutool进行AES加密解密的方法举例》AES是一种对称加密,所谓对称加密就是加密与解密使用的秘钥是一个,下面:本文主要介绍Java中使用Hutool进行AES加密解密的相关资料... 目录前言一、Hutool简介与引入1.1 Hutool简介1.2 引入Hutool二、AES加密解密基础

使用Python将JSON,XML和YAML数据写入Excel文件

《使用Python将JSON,XML和YAML数据写入Excel文件》JSON、XML和YAML作为主流结构化数据格式,因其层次化表达能力和跨平台兼容性,已成为系统间数据交换的通用载体,本文将介绍如何... 目录如何使用python写入数据到Excel工作表用Python导入jsON数据到Excel工作表用

Pytest多环境切换的常见方法介绍

《Pytest多环境切换的常见方法介绍》Pytest作为自动化测试的主力框架,如何实现本地、测试、预发、生产环境的灵活切换,本文总结了通过pytest框架实现自由环境切换的几种方法,大家可以根据需要进... 目录1.pytest-base-url2.hooks函数3.yml和fixture结论你是否也遇到过

鸿蒙中Axios数据请求的封装和配置方法

《鸿蒙中Axios数据请求的封装和配置方法》:本文主要介绍鸿蒙中Axios数据请求的封装和配置方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录1.配置权限 应用级权限和系统级权限2.配置网络请求的代码3.下载在Entry中 下载AxIOS4.封装Htt

鸿蒙中@State的原理使用详解(HarmonyOS 5)

《鸿蒙中@State的原理使用详解(HarmonyOS5)》@State是HarmonyOSArkTS框架中用于管理组件状态的核心装饰器,其核心作用是实现数据驱动UI的响应式编程模式,本文给大家介绍... 目录一、@State在鸿蒙中是做什么的?二、@Spythontate的基本原理1. 依赖关系的收集2.

Python基础语法中defaultdict的使用小结

《Python基础语法中defaultdict的使用小结》Python的defaultdict是collections模块中提供的一种特殊的字典类型,它与普通的字典(dict)有着相似的功能,本文主要... 目录示例1示例2python的defaultdict是collections模块中提供的一种特殊的字

C++ Sort函数使用场景分析

《C++Sort函数使用场景分析》sort函数是algorithm库下的一个函数,sort函数是不稳定的,即大小相同的元素在排序后相对顺序可能发生改变,如果某些场景需要保持相同元素间的相对顺序,可使... 目录C++ Sort函数详解一、sort函数调用的两种方式二、sort函数使用场景三、sort函数排序

Redis实现延迟任务的三种方法详解

《Redis实现延迟任务的三种方法详解》延迟任务(DelayedTask)是指在未来的某个时间点,执行相应的任务,本文为大家整理了三种常见的实现方法,感兴趣的小伙伴可以参考一下... 目录1.前言2.Redis如何实现延迟任务3.代码实现3.1. 过期键通知事件实现3.2. 使用ZSet实现延迟任务3.3