- Home /
Reading files in Unity from different platform
I'm using JSON to store data.
As these data are required at the start of the game, I would like to read the file as soon as the game starts.
my JSON files are currently stored under /Asset/Resources/Tables/_.json
On PC, I am appending UnityEngine.Application.dataPath with rest of the subpaths to read data using native C# file I/O libraries (i.e. StreamReader)
However, it seems such technique does not work for Android.
What's the best way to store and read JSON files in Unity games that support multiple platforms?
Thanks in advance,
Answer by citizen_rafiq · Aug 30, 2013 at 03:45 PM
public static void CreateFile(string path, string fileName){ if(!File.Exists(path+"/"+fileName)){ File.Create(path+"/"+fileName).Dispose(); } }
public static void WriteFile(string path,string fileName,string data){ if(File.Exists(path+"/"+fileName)){ StreamWriter sw = new StreamWriter(path+"/"+fileName); sw.WriteLine(data); sw.Flush(); sw.Close(); }
}
public static string ReadFile(string path,string fileName){ string output=""; if(File.Exists(path+"/"+fileName)){ StreamReader sr = new StreamReader(path+"/"+fileName);
output=sr.ReadLine(); sr.Close(); } return output; }
public static string GetAppDataPathIOS(){
string path=Application.dataPath.Substring(0,Application.dataPath.Length-5);
path=path.Substring(0,path.LastIndexOf('/'));
return path+"/Documents";
}
public static string GetAppDataPathAndroid(){
return Application.persistentDataPath;
}
Answer by kilgore · Aug 30, 2013 at 04:08 PM
You may want to look into using Application.persistantData instead of Application.dataPath. I traced out the paths that persistantData gave on Windows and Android platform and these were the results I got:
Windows: "C:/Users/USERNAME/AppData/LocalLow/Company/ProductName"
Android(internal): "/data/data/com.Company.ProductName/files"
Android(external): "/storage/emulated/0/Android/data/com.Company.ProductName/files"
Your answer
Follow this Question
Related Questions
(Solved)StreamWriter Write line 0 Answers
Reading - Writing data to - from file? 2 Answers
Work with XML hidden for the user? 1 Answer
Best Storage Method 1 Answer