如何在Android或iPhone上本地访问Unity资源?

5

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

2个回答

6
  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
}

1
现在已经是2016年了,有没有更简单的方法来访问Android插件中StreamingAssets文件夹中的文件呢? - Piotr
这是2018年了...经过数小时的搜索,我仍在使用这种方法。它运行良好... - flankechen

0

运行时访问文件的权限仅限于Assets/Resources目录。放置在该目录中的所有内容都可以通过Resources.Load方法(doc)进行访问,但无法从文件夹外部获取任何内容。

在Assets/Resources文件夹内,您可以设置任意文件夹结构。我在iPhone项目中使用它来从预定义的文本文件构建关卡,效果非常好。


Resources.Load虽然不是本地方法。但是否有其他人能够提供一些关于在本地代码(例如iOS上的Objective C,Android(NDK)上的C ++)中从Assets/Resources加载的指导? - bleater
Assaf刚刚提供了另一种访问Assets/Resources文件夹之外数据的方法Unity手册 - Casabian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接