如何在Android或iPhone上原生访问Unity资产?

ars*_*nk2 2 iphone android assets unity-game-engine

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

小智 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
}
Run Code Online (Sandbox Code Playgroud)