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));
......
相关推荐
流星白龙11 分钟前
【MySQL高阶】16.行结构
android·mysql·adb
HQL_seven29 分钟前
Android 四大组件解析
android
Digitally31 分钟前
适用于安卓、iOS 和电脑的最新文件共享应用评测指南
android·ios·电脑
__Witheart__1 小时前
搭建编译 HW-T3568 安卓固件的环境
android
Bowen_J1 小时前
Flutter 屏幕旋转适配
android·flutter·ios
程序员陆业聪9 小时前
绕过Frida/Xposed的最后防线:SVC直接系统调用与Native反Hook实战
android
程序员陆业聪10 小时前
WebView与原生JS交互:JSBridge生产级实现与安全防护
android
winlife_12 小时前
在 Unity 里用 AI 做游戏:funplay-unity-mcp 从安装到第一次让 AI 改场景
人工智能·游戏·unity·ai编程·claude·mcp
qq_2052790513 小时前
Unity 运行时候会时不时卡顿一下,哪怕是空场景
unity·游戏引擎
我命由我1234513 小时前
Android 开发问题:MlKitException: An internal error occurred during initialization.
android·java·java-ee·android jetpack·android-studio·androidx·android runtime