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?
Asked
Active
Viewed 1.7k times
2 Answers
6
- 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.
- 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
}
-
1It's 2016... is there easier solution for accessing files from StreamingAssets in Android plugins? – Piotr Oct 10 '16 at 09:50
-
it's 2018... after hours of search, I am still using this method. it works well... – flankechen Aug 21 '18 at 07:44
0
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.

Kay
- 12,918
- 4
- 55
- 77
-
Resources.Load is not a native method though. Does anyone else care to offer some guidance on loading from Assets/Resources in native code (e.g. Objective C on iOS, C++ on Android (NDK))? – bleater Jun 14 '12 at 03:26
-
Assaf just provided another method to access data outside Assets/Resources folder [Unity Manual](http://docs.unity3d.com/Manual/StreamingAssets.html) – Casabian Sep 02 '14 at 10:56