How to access Unity assets natively on Android or

2019-01-24 22:04发布

问题:

I need to access a file natively (from C++ or Java code) on Android and iPhone in a Unity plugin project. Does Unity provide any method to access files in the project Assets?

回答1:

  1. My workaround was to copy the files from the Application.streamingAssetsPath (which is inside a jar and can`t be accessed by most native libraries) to the Application.persistentDataPath (which is totally fine)and then to pass that path to the native code.
  2. The source files in the project should be under Assets\StreamingAssets

Small sample code in c# to copy files async: Add this method to a script which inherits 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
}


回答2:

Access to files at runtime is limited to directory Assets/Resources. Everything placed in there can be accessed by Resources.Load method (doc) but there is no chance to get something from outside the folder.

Within Assets/Resources folder you can set up an arbitrary folder structure. I used it in an iPhone project for level building from predefined text files and it worked like a charm.