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));
......
相关推荐
寰宇星城3 小时前
AppActuator - 让 AI Agent 直接理解并操作运行中的 Android App
android
波罗丁牌3 小时前
uni-app 实现视频聊天、屏幕分享,支持Android、HarmonyOS、iOS
android·uni-app·音视频
峥嵘life3 小时前
Android WiFi 热点 Channel 信道 和 Frequency 频率 转换总结
android·开发语言
是嘟嘟啊3 小时前
【Unity DOTS】EntityCommandBuffer 与 JobHandle
unity·ecs·dots·unity dots·job·burst·burstjob
jieyucx3 小时前
【高级利用】条件竞争与逻辑漏洞:与服务器赛跑的艺术
android·运维·服务器·web安全·文件上传
xcLeigh4 小时前
Unity基础:Camera相机组件详解——透视投影与正交投影的区别
数码相机·unity·游戏引擎
叶辞树5 小时前
死锁问题分析
android
TimeFine6 小时前
让 Codex “用上”Android Studio:JetBrains MCP Server 接入与实践
android
玖玥拾6 小时前
Unity3D RPG 入门项目(二)移动 Bug 修复、环绕相机、NPC 任务系统、UI 穿透处理
unity·游戏引擎
__Witheart__7 小时前
3568 Android 设置首次烧录后 usb otg 口模式
android·adb·rockchip