【问题标题】:How to access Unity assets natively on Android or iPhone?如何在 Android 或 iPhone 上本地访问 Unity 资产?
【发布时间】:2011-11-23 18:00:12
【问题描述】:

我需要在 Unity 插件项目中本地访问 Android 和 iPhone 上的文件(从 C++ 或 Java 代码)。 Unity 是否提供任何方法来访问项目 Assets 中的文件?

【问题讨论】:

    标签: android iphone unity3d assets


    【解决方案1】:
    1. 我的解决方法是将文件从 Application.streamingAssetsPath(位于 jar 中,大多数本机库无法访问)复制到 Application.persistentDataPath(完全没问题),然后将该路径传递给本机代码。
    2. 项目中的源文件应该在 Assets\StreamingAssets 下

    c# 中用于异步复制文件的小示例代码: 将此方法添加到继承 MonoBehaviour 的脚本中

    IEnumerator CopyFileAsyncOnAndroid()
    {
        string fromPath = Application.streamingAssetsPath +"/";
        //In Android = "jar:file://" + Application.dataPath + "!/assets/" 
        string toPath =   Application.persistentDataPath +"/";
    
        string[] filesNamesToCopy = new string[] { "a.txt" ,"b.txt"};
        foreach (string fileName in filesNamesToCopy)
        {
            Debug.Log("copying from "+ fromPath + fileName +" to "+ toPath);
            WWW www1 = new WWW( fromPath +fileName);
            yield return www1;
            Debug.Log("yield done");
            File.WriteAllBytes(toPath+ fileName, www1.bytes);
            Debug.Log("file copy done");
        }
        //ADD YOUR CALL TO NATIVE CODE HERE
        //Note: 4 small files can take a second to finish copy. so do it once and
        //set a persistent flag to know you don`t need to call it again
    }
    

    【讨论】:

    • 现在是 2016 年......有没有更简单的解决方案可以从 Android 插件中的 StreamingAssets 访问文件?
    • 现在是 2018 年......经过数小时的搜索,我仍在使用这种方法。它运作良好......
    【解决方案2】:

    在运行时对文件的访问仅限于目录 Assets/Resources。放在那里的所有东西都可以通过Resources.Load方法(doc)访问,但是没有机会从文件夹外获取东西。

    在 Assets/Resources 文件夹中,您可以设置任意文件夹结构。我在一个 iPhone 项目中使用它从预定义的文本文件中构建关卡,它的作用就像一个魅力。

    【讨论】:

    • Resources.Load 不是本机方法。有没有其他人愿意提供一些关于从原生代码中加载资产/资源的指导(例如 iOS 上的 Objective C、Android 上的 C++ (NDK))?
    • Assaf 刚刚提供了另一种访问 Assets/Resources 文件夹外数据的方法 Unity Manual
    猜你喜欢
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-11
    • 1970-01-01
    • 1970-01-01
    • 2020-10-20
    相关资源
    最近更新 更多