Search Unity

  1. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

Simple File creating + Overwriting

Discussion in 'Scripting' started by eTag96, Sep 12, 2011.

  1. eTag96

    eTag96

    Joined:
    Oct 24, 2010
    Posts:
    110
    Is there something wrong with this code:


    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System;
    4. using System.IO;
    5.  
    6. public class Files : MonoBehaviour {
    7.     public string filename="";
    8.     public string[] args;
    9.    
    10.     void Update() {
    11.         if(Input.GetKeyDown("t")) {
    12.             Read(args);
    13.         }
    14.     }
    15.    
    16.     void Read(string[] strs) {
    17.         StreamWriter w = File.AppendText(Application.persistentDataPath+"/"+filename+".txt");
    18.         foreach(string s in strs) {
    19.             Log(s, w);
    20.         }
    21.         w.Close();
    22.        
    23.         StreamReader r = File.OpenText(Application.persistentDataPath+"/"+filename+".txt");
    24.         DumpLog(r);
    25.         r.Close();
    26.     }
    27.    
    28.     void Log(string logMessage, TextWriter w) {
    29.         w.Write("\r\n"+logMessage);
    30.         w.Flush();
    31.     }
    32.    
    33.     void DumpLog(StreamReader r) {
    34.         string line = r.ReadLine();
    35.         while(line != null) {
    36.             Debug.Log(line);
    37.         }
    38.         r.Close();
    39.     }
    40. }

    because for some reason, everytime I hit "t", Unity freezes, but the file is created and all of the info is in the file.... is there something I'm missing? a Close(); somewhere?
     
  2. Ntero

    Ntero

    Joined:
    Apr 29, 2010
    Posts:
    1,436
    Yes, DumpLog() is not reading a new line within the While loop, and is permanently looping reading the initial line. ReadLine() should occur within the while loop.
     
  3. eTag96

    eTag96

    Joined:
    Oct 24, 2010
    Posts:
    110
    Wow. ok, thanks! works perfectly.
     
  4. majmun

    majmun

    Joined:
    Feb 2, 2011
    Posts:
    140
    I want to learn how to make .txt files on my computer with unity application :( I'm doing everything with Playerprefs
     
unityunity