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权限不可访问。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小码哥儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值