Search code examples
androidiphoneunity-game-engineassets

How to access Unity assets natively on Android or iPhone?


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?


Solution

    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
    }