Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Append data to a text file without closing/reopening the text file every FixedUpdate()

Discussion in 'Scripting' started by Whirly123, Sep 14, 2017.

  1. Whirly123

    Whirly123

    Joined:
    Jun 18, 2016
    Posts:
    3
    I am trying to record the coordinates of the position of an object into a text file and my code is working fine and doing what I want. However, the way it is set up will keep opening and closing the file every time it writes a new line which seems unnecessary and hard drive intensive. My code looks like this:

    When the key "1" is pressed, collectdata = true for 410 seconds. Writing to the text file begins and then after that amount of time it stops.

    Code (CSharp):
    1. void Start ()
    2.         {
    3.             filePath = Path.Combine(Application.dataPath, folderName);
    4.             filePath = Path.Combine(filePath, fileName);
    5.             textFile = new FileInfo (filePath);
    6.         }
    7.      
    8.  
    9.     void FixedUpdate()
    10.         {
    11.             GameObject ROOMDATA = GameObject.FindGameObjectWithTag ("ROOMDATA");
    12.             if (collectData == true)
    13.             {
    14.                 writer = textFile.AppendText ();
    15.                 float x = ROOMDATA.transform.position.x;
    16.                 float z = ROOMDATA.transform.position.z;
    17.                 writer.WriteLine (x + "\t" + z);
    18.                 Debug.Log ("write to file");
    19.             writer.close
    20.         }
    21.          
    22.          }
    23.  
    24.     void Update ()
    25.         {
    26.         // Pressing 1 saves roomdata1
    27.         if (Input.GetKeyDown ("1")) {
    28.             collectData = true;
    29.             StartCoroutine (WaitAndStop ());
    30.             }
    31.  
    32.         }
    33.     IEnumerator WaitAndStop()
    34.     {
    35.         yield return new WaitForSeconds(410);
    36.         collectData = false;
    37.  
    38.     }
    39. }
     
  2. kietus

    kietus

    Joined:
    Jun 4, 2013
    Posts:
    54
    Why do you need to write it every frame ? If there no special reasons, you should store data to a variable, and write the file when WaitAndStop end.
     
  3. Whirly123

    Whirly123

    Joined:
    Jun 18, 2016
    Posts:
    3
    That's exactly what I need to do :)