-2
\$\begingroup\$

I have a Unity C# Script which updates a variable each time the Update function is called. I would like to know how to write to a file from the update function.

\$\endgroup\$
6
\$\begingroup\$

Although I wholeheartedly agree with @Jon on this one I'm still going to answer your question. The following class will write to a file in the Update method. Have fun with it.

using UnityEngine;
using System.IO;
public class VeryBadIdea : MonoBehaviour {

    private string filename = "WeWLad.txt";
    private float some_variable;
    private string textToWrite = "Variables : ";
    // Update is called once per frame
    void Update () {
        some_variable += Time.deltaTime;//update the variable with something;
        textToWrite = textToWrite + " " + some_variable.ToString();//create a proper string so we can read the file afterwards
        File.AppendAllText(filename, textToWrite);//write to the file. No need to call Flush or Close. Note this does NOT overwrite the file every time you restart the game
    }
}

Alternatively this might be a better solution.

using System.IO;
using System.Collections.Generic;
using UnityEngine;
public class SlightlyBetterIdea : MonoBehaviour {
    List<SomeDataToWrite> listToHoldData;
    private float var1,var2 ;// Some variables to increment;
    private string filename = "WeWLad.txt";
    void Start()
    {
        listToHoldData = new List<SomeDataToWrite>();
    }
    // Update is called once per frame
    void Update () {
        //Increment the variables
        var1 += Time.deltaTime;
        var2 += Time.deltaTime;
        //Add them to our handy dandy list
        listToHoldData.Add(new SomeDataToWrite(var1, var2));
    }
    void OnApplicationQuit()//Now that we are quiting the application we can write our data to a file
    {
        string textToWrite="GLORIOUS DATA" +"\r\n";
        foreach(SomeDataToWrite data in listToHoldData)
        {
            textToWrite = textToWrite + " x:" + data.x + " y:" + data.y +"\r\n"; 
        }
        File.AppendAllText(filename, textToWrite);
    }
     internal class SomeDataToWrite
    {
        internal float x;
        internal float y;
        internal SomeDataToWrite(float x, float y)
        {
            this.x = x;
            this.y = y;
        }
    }
}
\$\endgroup\$
  • 1
    \$\begingroup\$ Why would you guess that he uses the filestream class? There's no reference to it anywhere in the code, he's using File.AppendAllText as the code states. Also why would it create thread exceptions? There is no threading going on in it. \$\endgroup\$ – Kevin Jun 21 '16 at 13:30
  • 1
    \$\begingroup\$ I'm using the File class as you can see from the code not the FileStream class. What AppendAllText does under the hood you should ask Microsoft :D. Besides AppendAllText is guaranteed to close the file handle even if a exception is raised so you dont have anything to worry. \$\endgroup\$ – Uri Popov Jun 21 '16 at 13:30
  • 1
    \$\begingroup\$ You don't have to ask Microsoft, you can just look it up here: referencesource.microsoft.com/#mscorlib/System/io/file.cs And it uses StreamWriter internally. \$\endgroup\$ – jgallant Jun 21 '16 at 13:43
  • 1
    \$\begingroup\$ @user3927312 no, that is not correct. All the Monobehaviour methods in Unity typically run on a single thread. There's a separate loading thread and some multithreading under the hood in the physics and rendering systems, but that's about it unless you manually start a new thread of your own. \$\endgroup\$ – DMGregory Jun 21 '16 at 14:04
  • 1
    \$\begingroup\$ look no offence or anything but if you asking with help on how to write to files you are far away from understanding threads. Btw check my second example it might be what you are looking for. \$\endgroup\$ – Uri Popov Jun 21 '16 at 14:23
4
\$\begingroup\$

You do not want to write to a file inside of Update(). That is bad design, and ridiculous. Instead, you may want to consider writing to memory in your Update() function -- and then dumping this data to file at a reasonable opportunity.

\$\endgroup\$
  • \$\begingroup\$ I actually only need to do this to cache the values of a sin function. I'll put the values into an array and remove the file writing component. i just need a quick way to record around 500-1000 values and save it. \$\endgroup\$ – user3927312 Jun 21 '16 at 13:15
  • 3
    \$\begingroup\$ Create a function that will write your data to file, and only call it once, when needed. \$\endgroup\$ – jgallant Jun 21 '16 at 13:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.