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));
......
相关推荐
梦里花开知多少5 分钟前
浅谈ThreadPool
android·面试
帅次10 分钟前
单例初始化中的耗时操作如何拖死主线程
android·webview·android runtime
WarrenMondeville33 分钟前
5.Unity面向对象-依赖倒置原则
unity·设计模式·依赖倒置原则
用户08748819991739 分钟前
Android 资源类型全解析及四大常用布局资源深度指南
android
火锅鸡的味道1 小时前
解决AOSP工程Android Studio打开卡顿
android·python·android studio
2501_915921431 小时前
2026 iOS 上架新趋势 iOS 发布流程模块化
android·ios·小程序·https·uni-app·iphone·webview
毕设源码-钟学长1 小时前
【开题答辩全过程】以 基于Android的高校二手交易系统为例,包含答辩的问题和答案
android
FLEMMINGS1 小时前
当 Android Studio 模拟器提示emulator failed to connect within 5 minutes
android·ide·android studio
鹏程十八少1 小时前
6. Android Shadow与众不同?一文解决插件化四大核心难题:ClassLoader冲突、Activity代理、资源隔离、动态更新(源码分析上)
android·前端·面试
万兴丶1 小时前
Unity 用AI自动开发游戏近一年----最新Cursor使用心得
人工智能·游戏·unity·cursor