- Home /
The question is answered, right answer was accepted
Saving data in to files (Android)
Hey, I'm trying to save information on files using these methods, here's the code:
using System.IO
public class scoreFile
{
private int[] level;
private bool[] completed;
private float[] completionTime;
private string[] scores;
private string fileName;
//This class stores information for each of the levels.
public scoreFile(int num)
{
fileName = "scores.txt";
try
{
if (!File.Exists(fileName))
{
level = new int[num];
completionTime = new float[num];
completed = new bool[num];
scores = new string[num];
Debug.Log("Opened file!");
for (int i = 0; i < num; i++)
{
level[i] = i + 1;
completionTime[i] = 0;
completed[i] = false;
scores[i] = level[i] + " " + 0 + " " + completionTime[i];
}
Debug.Log("About to write into file!");
File.WriteAllLines(fileName, scores);
}
else
{
Debug.Log("File is exist! Loading!");
loadFile();
}
}
catch (System.Exception e)
{
Debug.Log(e);
}
}
public bool isComplete(int i) { return completed[i]; }
public int levels(int i) { return level[i - 1] + 1; }
public float timeScore(int i) { return completionTime[i]; }
public void loadFile()
{
Debug.Log("Reading");
string[] levelsInfo = File.ReadAllLines(fileName);
int num = levelsInfo.Length;
level = new int[num];
completionTime = new float[num];
completed = new bool[num];
for (int i = 0; i < num; i++)
{
//Debug.Log(levelsInfo[i]);
string str = levelsInfo[i];
level[i] = (int)int.Parse(str.Substring(0, 1));
int f = int.Parse(str.Substring(2, 1));
if (f == 0)
completed[i] = false;
else
completed[i] = true;
completionTime[i] = (float)float.Parse(str.Substring(4));
}
}
}
It works great on Unity3D, but doesn't on my android mobile device (Nexus 4) is it because im using TXT extension? I don't understand whats the issue.
Answer by Ranger-Ori · Sep 23, 2013 at 12:17 PM
Found the solution, should save the files in Application.persistentDataPath
which means the code should have looked like:
private string filePath = Application.persistentDataPath + "/settings.txt";
Also set the Write Access to External (SDCard) when you put the app on your phone. This option is found in Player Settings > Other Settings
The line
private string filePath = Application.persistentDataPath + "/settings.txt";
should replace this?
File.WriteAllLines(fileName, scores);
Did you figure out if your assumption was correct? The accepted answer was too vague.
Yeah.. the right way to reference a path is with the line
private string filePath = Application.persistentDataPath + "/settings.txt";
Follow this Question
Related Questions
file read/write in Android devices(phone/tablet...) 1 Answer
How to tell android to open a file 0 Answers
Android and XML (Reading/Wirting) 1 Answer
Dat File Location 1 Answer
Access file in Android with Streamreader 0 Answers