Unity: Reading files in Streaming Assets

Posted by matheus@guimak.com |17 Sep 17 | 0 comments

Streaming Assets can be a great location to store your custom data files, especially those precious jsons used for loading scriptable levels and other configurations. However, much like PlayerPrefs, each platform stores them in their own path. Unity comes to the rescue and provides a neat shortcut Application.streamingAssetsPath  so you don’t have to care. fantastic, eh? only one problem: some platforms may also stores those files in different ways, notably: Android. 

Android packs all contents of Streaming Assets into a jar file which you must unpack before accessing. This means you cannot simply do a simple File.ReadAllText(Application.streamingAssetsPath + “/”  + filePath) on the Droid. You must use Unity’s WWW class so it can unpack the file first and then read the text in it.

Since Unity refuses to abstract it, at least for now, here’s my utility class that hopefully will be of some help to someone.

public static class StreamingAssetsReader

{

public static string Read(string filePath)

{

string result = null;

string path = string.Format(“{0}/{1}”, Application.streamingAssetsPath, filePath);

 

if (Application.platform == RuntimePlatform.Android)

{

WWW reader = new WWW(path);

while (!reader.isDone)

{
//yes, as dumb as this code looks, you’re not reading it wrong – this is an empty loop. there’s no other way to run the reader to the end as far as I know

}

result = reader.text;

}

else

{

result = File.ReadAllText(path);

}

 

return result;

}

}



                    
                        

Leave a Reply

Your email address will not be published. Required fields are marked *