AssetBundle in Pico(Android)

编程入门 行业动态 更新时间:2024-10-24 15:14:38

<a href=https://www.elefans.com/category/jswz/34/1712460.html style=AssetBundle in Pico(Android)"/>

AssetBundle in Pico(Android)

VR一体机的项目,经常会需要把静态大型资源(prefab/scene)打包成assetbundle并保存在一体机的存储空间中,
让应用程序在一体机运行的时候,读取assetbundle的静态资源。

1. assetbundle的生成

using UnityEditor;
using System.IO;public class CreateAssetBundles
{// 生成menu[MenuItem("Assets/Build AssetBundles")]static void BuildAllAssetBundles(){// 指定生成的ab包的流资源文件夹,StreamingAssets文件夹是Unity和Android的约定好的对接文件夹// 当build and run时,项目中的StreamingAssets文件夹中的ab包会同步传输到 Pico中// 的Application.streamingAssetsPath文件夹中,并打包成jarstring assetBundleDirectory = "Assets/StreamingAssets";if (!Directory.Exists(assetBundleDirectory)){Directory.CreateDirectory(assetBundleDirectory);}// 生成ab包的代码,BuildTarget.Android是因为我们运行在Pico上,平台是androidBuildPipeline.BuildAssetBundles(assetBundleDirectory,BuildAssetBundleOptions.None,BuildTarget.Android);}
}

当编辑完代码之后,会发现unity editor导航栏中Assets选项下面会出现Build AssetBundles的功能按钮

找到预制体,为即将打出的ab包命名

在Assets导航栏下,单击Build AssetBundles

之后,在项目中的Assets下就会生成StreamingAssets文件夹,并且文件夹内也会有打包好的ab包。

完成这些,就可以Build and run了

完成后Pico中的应用程序包中,多了一份jar文件,这个jar文件就是过程中在Pico中生成的ab包jar文件,这个文件的访问权限只有在应用程序中。

2. AssetBundle的读取

using UnityEngine;
using System.IO;public class LoadFromFileExample : MonoBehaviour
{void Start(){// 生成的cubee ab包在pico的应用程序的流文件夹中var streampath = Path.Combine(Application.streamingAssetsPath, "cubee");// 使用LoadFromFile读取ab包var myLoadedAssetBundle = AssetBundle.LoadFromFile(streampath);if (myLoadedAssetBundle == null){Debug.Log("Failed to load AssetBundle!");return;}// 在ab包中加载预制体的名称var prefab = myLoadedAssetBundle.LoadAsset<GameObject>("Cube");Instantiate(prefab);}
}

观察pico,发现scene中,的预制体被加载出来了

tips:如果ab包打的是scene,那么在LoadFromFile后得到的ab包需要用到这部分代码来加载场景

        var myLoadedAssetBundle = AssetBundle.LoadFromFile(streampath);string[] scene = myLoadedAssetBundle.GetAllScenePaths();SceneManager.LoadScene(scene[0],LoadSceneMode.Additive);

note:聊一下 Application的几个path
Application.dataPath
Applicatioin.persistentDataPath
Application.streamingAssetsPath

/sdcard是内部共享存储空间文件夹,也等价于/storage/emulated/0,即:

data是 平行于内部共享储蓄空间的文件夹,用于存储apk数据,非root权限不可访问。


streamingAssetsPath 是将data文件夹打成jar包了

更多推荐

AssetBundle in Pico(Android)

本文发布于:2024-02-17 15:13:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1694483.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:AssetBundle   Pico   Android

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!