- Home /
Saving items to a text file
I'm trying to code a saving system where it takes a variable from each item that contains the tag "planet2" and save it to a text file. I have a good ammount coded, but the problem is that when I run it, and it saves. I open the text file only to find that it is empty.
var pla : GameObject[];
var directory = "Saves";
var save1 = "Saves/planets.txt";
function Start () {
if (!System.IO.Directory.Exists(save1) ){
System.IO.Directory.CreateDirectory(directory);
save();
}
}
function Update () {
savingtimer ++;
if(savingtimer >= 5000){
save();
savingtimer = 0;
}
}
function save(){
if(pla == null){
pla = GameObject.FindGameObjectsWithTag("planet2");
}
for(var planet2 in pla){
planets.Add(planet2);
}
planets.Add (GameObject.FindGameObjectsWithTag("planet2"));
for(var pln :GameObject in pla){
var sw = new StreamWriter(save1);
var pls : planetbehave = pln.GetComponent(planetbehave);
sw.WriteLine("" + pls.pname + "\n");
sw.Flush();
sw.Close();
}
}
Answer by yoyo · Dec 12, 2012 at 06:25 AM
Looks like you are rewriting the file with each object in pla, so at most the file will nly contain the information from the last object in the list. You should move the "new StreamWriter" before the start of the loop, and the Flush/Close after the end of the loop.
You should also try connecting MonoDevelop to Unity (Run menu > Attach), set a breakpoint on the save method (put cursor on first line and press F9), and step through it (F11) to make sure it's doing what you expect. Alternatively, put a Debug.Log message as your write each line, to make sure it's actually running.
Your answer
Follow this Question
Related Questions
Load function not working propperly? 1 Answer
Loading from multiple files? 2 Answers
Android Multitouch 0 Answers
Object deformation on activat 0 Answers
About ListItems in Unity3D 1 Answer