Search Unity

Using StreamWriter to log realtime GameObject coordinates

Discussion in 'Scripting' started by Theformand, Apr 14, 2011.

  1. Theformand

    Theformand

    Joined:
    Jan 2, 2010
    Posts:
    271
    [SOLVED]


    Hey folks!

    Im trying to log the X, Y, and Z coordinates of two cubes (for starters), and I would like to log these coordinates to a textfile, during Update() and for as long as the application is running. It wont run for very long, but thats beside the point. Ive scripted this so far, which gives me a new textfile in my project library, but nothing is actually written to it:

    Code (csharp):
    1. import System.IO;
    2. import System;
    3.  
    4. var Lx: float;
    5. var Ly: float;
    6. var Lz: float;
    7. var Rx: float;
    8. var Ry: float;
    9. var Rz: float;
    10. var coordText: String;
    11. var path: String;
    12. var sW;
    13.  
    14. function Start () {
    15. sW = new StreamWriter("TestFile.txt");
    16.  
    17.     }
    18.  
    19. function Update () {
    20.  
    21. Rx = gameObject.Find("Rhand").transform.position.x;
    22. Ry = gameObject.Find("Rhand").transform.position.y;
    23. Rz = gameObject.Find("Rhand").transform.position.z;
    24. Lx = gameObject.Find("Lhand").transform.position.x;
    25. Ly = gameObject.Find("Lhand").transform.position.y;
    26. Lz = gameObject.Find("Lhand").transform.position.z;
    27.  
    28. coordText =  Rx +"," + Ry + "," + Rz +"," + Lx +","+ Ly+ ","+Lz;
    29.  
    30. if(Input.GetKeyDown("b")){
    31. WriteFile();
    32. }
    33.  
    34. }
    35.  
    36. function WriteFile(){
    37. sW.WriteLine(coordText);
    38.  
    39. }
    I suspect it is because im not doing sW.Close(); at any point in time, but im not sure where I should do this? if I do it in update, it will close every frame, which is not desirable I guess? Ive taken a look at other forum posts and examples, but none of them seem to write anything in realtime, its mostly done once in the Start() function, so Im confuzzled =)

    EDIT: Solved it by using Input.GetButtonDown instead =)
    Also added sW.Flush() to the WriteFile() function, which works like a charm. Every frame, the XYZ of both gameobjects are being logged to my textfile
     
    Last edited: Apr 14, 2011