Unity安卓Android从StreamingAssets加载AssetBundle

在安卓下无法获取StreamingAssets目录下所有目录和文件名,所以需要提前将文件名整理成一个文件filelist.txt。

1.用批处理命令将StreamingAssets下所有文件名输出到filelist.txt中

chcp 65001是使用UTF-8编码,否则中文是乱码。

复制代码
@echo off
chcp 65001
dir /b /s /a-d > filelist.txt

2.将filelist.txt中绝对路径转换成相对路径

打开filelist.txt,去掉StreamingAssets

3.确何filelist.txt为UTF-8

4.复制StreamingAssets目录下所有文件到PersistentData

cs 复制代码
void Start () {
    CopySteamingAssetsFileToPersistentDataPath();
}

void CopySteamingAssetsFileToPersistentDataPath()
{
    string listFile = Path.Combine(Application.streamingAssetsPath, "filelist.txt");
    WWW reader = new WWW(listFile);
    while (!reader.isDone) { }

    string textString = reader.text;
    Debug.Log(textString.Length);
    List<string> striparr = textString.Split(new string[] { "\r\n" }, StringSplitOptions.None).ToList();
    List<string> lines = striparr.Where(s => !string.IsNullOrEmpty(s)).ToList();

    for (int i = 0; i < lines.Count; i++)
    {
        string srcfile = Path.Combine(Application.streamingAssetsPath, lines[i]);
        WWW reader1 = new WWW(srcfile);
        while (!reader1.isDone) { }

        string dstFile = Path.Combine(Application.persistentDataPath, lines[i]);

        //安卓的路径只能是/,反斜杠\无效
        dstFile = dstFile.Replace('\\','/');
        string dir = Path.GetDirectoryName(dstFile);

        if (!Directory.Exists(dir))
        {
            Directory.CreateDirectory(dir);
            Debug.Log(dstFile);
        }
        File.WriteAllBytes(dstFile, reader1.bytes);
    }
}

5.AssetBundle资源需要针对Android单独打包,与Windows的不通用。

打包完将资源复制到StreamingAssets下

cs 复制代码
ROBOCOPY Android  ..\Assets\StreamingAssets\Android  /E

加载AssetBundle

cs 复制代码
//存放AssetBundle的根目录名字
    private static string rootFolder = "Android";
    //本地资源路径
    public string AbPath
    { get
        {
            string path =
#if UNITY_ANDROID && !UNITY_EDITOR
             Application.persistentDataPath + "/";
#else
             Application.streamingAssetsPath + "/";
#endif
            return string.Format("{0}{1}/", path, rootFolder);
        }
    }
cs 复制代码
AssetBundle assetBundle = AssetBundle.LoadFromFile(string.Format("{0}{1}", AbPath, rootFolder));
......
相关推荐
tangweiguo0305198722 分钟前
Android 混合开发实战:统一 View 与 Compose 的浅色/深色主题方案
android
老狼孩1112231 分钟前
2025新版懒人精灵零基础及各板块核心系统视频教程-全分辨率免ROOT自动化开发
android·机器人·自动化·lua·脚本开发·懒人精灵·免root开发
打死不学Java代码1 小时前
PaginationInnerInterceptor使用(Mybatis-plus分页)
android·java·mybatis
IT乐手3 小时前
android 解决系统级应用 WebView 加载崩溃的问题
android
Kapaseker3 小时前
Kotlin泛型精解:类型世界的奇幻之旅
android·kotlin
顾林海3 小时前
深入探究 Android Native 代码的崩溃捕获机制
android·面试·性能优化
爱分享的程序员4 小时前
前端跨端框架的开发以及IOS和安卓的开发流程和打包上架的详细流程
android·前端·ios
thigh_d4 小时前
uniapp 安卓离线本地打包,Android Studio生成apk包
android·uni-app·android studio
二J6 小时前
管理100个小程序-很难吗
android·小程序
s11show_1636 小时前
hz修改后台新增keyword功能
android·java·前端