- Home /
Trying to save and load from a text file on android.
This what I have written so far and it works fine in the editor but when I try it on my android phone it doesnt work. So what am I doing wrong?
using UnityEngine; using System.Collections; using System.IO; using System.Text;
public class AndroidScoreSavingTest : MonoBehaviour {
string message;
string loadMessage = "Yeah working";
string data;
FileInfo f;
void Start()
{
f = new FileInfo(Application.dataPath + "\\" + "myFile.txt");
Screen.SetResolution(800, 600, true);
}
void OnGUI()
{
GUILayout.BeginArea(new Rect(0,0,500,500));
GUILayout.Label(message + " " + data);
if(GUILayout.Button("Save"))
{
if(!f.Exists)
{
message = "Creating File";
Save();
}
else
{
message = "Saving";
Save();
}
}
if(GUILayout.Button("Load"))
{
if(f.Exists)
{
Load();
}
else
{
message = "No File found";
}
}
GUILayout.EndArea();
}
void Save()
{
StreamWriter w;
if(!f.Exists)
{
w = f.CreateText();
}
else
{
f.Delete();
w = f.CreateText();
}
w.WriteLine(loadMessage);
w.Close();
}
void Load()
{
StreamReader r = File.OpenText(Application.dataPath + "\\" + "myFile.txt");
string info = r.ReadToEnd();
r.Close();
data = info;
}
}
Your Load() method was exactly what I was looking for. Thanks for that!
Answer by GameVortex · Nov 18, 2013 at 07:01 PM
On android you might not have direct write access to the dataPath of the project.
Try using Application.persistentDataPath instead. This is where save files are intended to be stored.
That is great! Could you mark it as answered so it gets removed from the unanswered section? =)
Answer by TheMaster001 · Mar 11, 2018 at 01:38 PM
yep that worked need to change the Application.dataPath to Application.persistentDataPath like you said and it worked a treat , many thanks
Answer by AquinoJ · Apr 10, 2019 at 08:41 PM
I needed to load json and similar text files into my Android game. Unfortunately I could not access the internal memory from the Application.persistentDataPath, so when I searched, I found this amazing tool that helped me use these functions, and it only cost $ 9.90. Now I can read and write files in internal memory, manage files and folders, and so on.
https://assetstore.unity.com/packages/tools/integration/native-android-toolkit-mt-139365
I hope this helps anyone who is reading in the future!
Your answer
Follow this Question
Related Questions
Saving and loading to/from Android 1 Answer
Saving frequently throughout game lifecycle (Android) 1 Answer
Saving And Loading on Android 0 Answers
JSON file not written/read on application exit on android 1 Answer
Serializing a graph 2 Answers