我需要在 Android 和 iPhone 上的 Unity 插件项目中本地访问文件(从 C++ 或 Java 代码)。 Unity 是否提供任何方法来访问项目资源中的文件?
最佳答案
- 我的解决方法是将文件从 Application.streamingAssetsPath(位于 jar 中,大多数 native 库无法访问)复制到 Application.persistentDataPath(完全没问题),然后将该路径传递给 native 代码。
- 项目中的源文件应该在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
}
关于android - 如何在 Android 或 iPhone 上原生访问 Unity Assets ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8246917/