• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by angelonc · Apr 07, 2015 at 12:41 AM · streamingwriting to text

Help writing to file every update

I'm trying to save my players position every frame.

I'm having some trouble getting this to work... StreamWriter seems to only work when it is within a function, and I can't get it to, say, open a StreamWriter during Start() and then write lines during Update().

However, something is going wrong, here's the code:

 import System;
 import System.IO;
 var Subject : int = 99;        
  
 function Start() {
 
     var fileName = "NavData/sub" + Subject + "_nav.txt";
     var sw : TextWriter = new StreamWriter(fileName,true);
     
     if (File.Exists(fileName))
     {
         Debug.Log(fileName+" already exists.");
         //EditorApplication.isPlaying = false;
     }
     
     
     // Write header
     sw.WriteLine ("tX tY tZ rX rY rZ time");
     sw.Flush();
 }
 
 function Update() {
     // Get object information
     var trans : Vector3 = transform.position; 
     var rot   : Vector3 = Quaternion.identity.eulerAngles;
     var ts = DateTime.Now;
     
     print(ts);
     
     //sw.WriteLine("test");
     //sw.Close();
 }

What you see above works, it writes a single line to file on start. However, if I uncomment

 sw.WriteLine("test");
 sw.Close();

I get the error: BCE0005: Unknown identifier: 'sw'.

I imagine this is because the StreamWriter is local to Start(), so when I move it outside of the Start() function, I instead get several errors.

Code:

 import System;
 import System.IO;
 var Subject : int = 99;
 var fileName = "NavData/sub" + Subject + "_nav.txt";
 var sw : TextWriter = new StreamWriter(fileName,true);        
  
 function Start() {
     
     if (File.Exists(fileName))
     {
         Debug.Log(fileName+" already exists.");
         //EditorApplication.isPlaying = false;
     }
     
     
     // Write header
     sw.WriteLine ("tX tY tZ rX rY rZ time");
     sw.Flush();
 }
 
 function Update() {
     // Get object information
     var trans : Vector3 = transform.position; 
     var rot   : Vector3 = Quaternion.identity.eulerAngles;
     var ts = DateTime.Now;
     
     print(ts);
     
     sw.WriteLine("test");
     sw.Close();
 }


I get one error on start: IOException: Sharing violation on path /Users/Chris/Documents/Classwork/Epstein_Rotation/LocalGeometry/Maze_Unity/NavData/sub99_nav.txt

And another error every frame:

NullReferenceException: Object reference not set to an instance of an object writeTestC.Update () (at Assets/Scripts/writePosition.js:29)

In this latter case, the file is made, but nothing is written to it...

Any help is appreciated, thanks in advance!

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

3 Replies

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by OrbitSoft · Apr 07, 2015 at 07:40 AM

I think that you should keep the StreamWriter null and then assign it in Start function like this:

 var sw : TextWriter = null;
 
 function Start()
 {
   // the stream writer is assigned
   sw = new StreamWriter(filename,true);
 }
 
 function Update()
 {
   sw.WriteLine("test");
   sw.Close();
 }
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
1

Answer by ethestel · Apr 07, 2015 at 07:56 AM

Hello,

Try instantiating StreamWriter object in your Start or Awake methods, and assign it to an instance variable.

 import System;
  import System.IO;
  var Subject : int = 99;
  var fileName = "NavData/sub" + Subject + "_nav.txt";
  var sw : TextWriter;       
   
  function Start() {
      
      sw = new StreamWriter(fileName,true); 
 
      if (File.Exists(fileName))
      {
          Debug.Log(fileName+" already exists.");
          //EditorApplication.isPlaying = false;
      }
      
      
      // Write header
      sw.WriteLine ("tX tY tZ rX rY rZ time");
      sw.Flush();
  }
  
  function Update() {
      // Get object information
      var trans : Vector3 = transform.position; 
      var rot   : Vector3 = Quaternion.identity.eulerAngles;
      var ts = DateTime.Now;
      
      print(ts);
      
      sw.WriteLine("test");
      sw.Close();
  }
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
1

Answer by angelonc · Apr 07, 2015 at 02:12 PM

Thanks for your answers!

I had tried what you suggested (instantiating in awake), but it wasn't working, and that was due to the file being improperly closed from the previous time running the code.

Got it running by tightening up my exit procedure and following your suggestions:

 import System;
 import System.IO;
 
 var sw : TextWriter = null;
             
  
 function Start() {
 
     var scene : String = Application.loadedLevelName;
     var sceneparts = scene.Split("_"[0]);
     var MazeNumber = int.Parse(sceneparts[1]);
     var fileName = "NavData/sub" + placeObjects.SubjectNumber + "_" + MazeNumber + "_nav.txt";
 
     sw = new StreamWriter(fileName);
     //Write header
     sw.WriteLine ("tX tY tZ rX rY rZ time");
     sw.Flush();
 }
 
 function Update() {
     // Get object information
     var tx = transform.position.x; 
     var ty = transform.position.y; 
     var tz = transform.position.z;
     var rx = transform.eulerAngles.x;
     var ry = transform.eulerAngles.y;
     var rz = transform.eulerAngles.z;
 
     var epochStart = new System.DateTime(1970, 1, 1, 0, 0, 0, System.DateTimeKind.Utc);
      var ts = (System.DateTime.UtcNow - epochStart).TotalSeconds;
     
     sw.WriteLine(tx.ToString("F2") + "," + ty.ToString("F2") + "," + tz.ToString("F2") + "," + rx.ToString("F2") + "," + ry.ToString("F2") + "," + rz.ToString("F2") + "," + ts);
     
     if (Input.GetKeyDown("escape")) {
         print('Quitting...');
         //EditorApplication.isPlaying = false;
         sw.Close();
         Application.LoadLevel("Menu");
     }
 }
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.



Follow this Question

Answers Answers and Comments

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

WEB game how in the dozens of songs quickly switch? There is a good way to do 1 Answer

Web radio playing inside unity? 2 Answers

Terrain.Light property removed? 1 Answer

[SOLVED]Send a variable to an object type variable by using Stream 1 Answer

Is it possibile to see, in browser, a stream of game play? 2 Answers

  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges