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文件夹中,并打包成jar
string assetBundleDirectory = "Assets/StreamingAssets";
if (!Directory.Exists(assetBundleDirectory))
{
Directory.CreateDirectory(assetBundleDirectory);
}
// 生成ab包的代码,BuildTarget.Android是因为我们运行在Pico上,平台是android
BuildPipeline.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包了
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
二维码