How to read text files in Android assemblies for Unity?
I am having trouble reading text files stored in the StreamingAsset folder on my Android phone when I create a game as an .apk file.
I know for Android you need to use a different path to access the files with
"jar:file://" + Application.dataPath + "!/assets" + fileName;
and save it in the WWW class. I tried many ways but nothing works for me as I am completely lost right now. My code looks like this:
void Awake(){
string filePath = "jar:file://" + Application.dataPath + "!/assets" + fileName;
// Reads our text file and stores it in the array
string[][] Level = readFile (filePath);
}
// Reads our level text file and stores the information in a jagged array, then returns that array
string[][] readFile(string file){
WWW loadFile = new WWW (file);
while (!loadFile.isDone) {}
string text = System.IO.File.ReadAllText(loadFile.text);
string[] lines = Regex.Split(text, "\r\n");
int rows = lines.Length;
string[][] levelBase = new string[rows][];
for (int i = 0; i < lines.Length; i++) {
string[] stringsOfLine = Regex.Split(lines[i], " ");
levelBase[i] = stringsOfLine;
}
return levelBase;
}
+3
source to share
2 answers
The line string text = System.IO.File.ReadAllText(loadFile.text);
is wrong:
-
loadFile.text
already contains the content of the file you are trying to open withSystem.IO.File.ReadAllText
- Also you cannot use method
System.IO.File.ReadAllText
to access file from StreamingAssets on Android.
-1
source to share