0

I created a Scene in Unity using VR and I want to track the Position of the User and save it to a CSV file. Since I only want the Position of the for certain Tasks I dont want to run the script for the whole Scene. So created a Script that enables and disables the script via a simple OnClick Event on a Button.

So I created a Script that enables and disables the script via a simple OnClick Event on a Button. The Problem that I have is that everytime I disable the script and enable it again there won't be another csv File that is created.

This is my Code:

public class Eins : MonoBehaviour
{
    string filePath = @"";
    string filename;
    string fullPath;
    string delimiter = "\t";
    StreamWriter sw;
    string[] output;
    string finalOutput;
    public GameObject Camera;
    private float timer = 0f;

    // Start is called before the first frame update
    void Start()
    {
        filename = "Results_" + DateTime.Now.ToString("yyyy-mm-dd-hh-ss") + "_" + ".txt" + "";
        filename = filename.Replace("/", "_");
        filename = filename.Replace(":", "_");
        filename = filename.Replace(" ", "_");
        fullPath = Path.Combine(filePath, filename);
        sw = new StreamWriter(fullPath, true);
    }

    // Update is called once per frame
    public void Update()
    {
        timer += Time.deltaTime;

        output = new string[]
        {   
            timer.ToString(),

            Camera.transform.position.x.ToString(), Camera.transform.position.z.ToString()


        };

        finalOutput = String.Join(delimiter, output);
        sw.WriteLine(finalOutput);
    }

So what I already found out is that the Problem is in the start function. Since it is called only once while the Scene is running, my file would be created only once. But actually I have no idea of how to solve this Problem, since I don't know how to have a function that will create a csv file everytime the script is enabled again.

I would really appreciate it if somebody could help me.

aybe
  • 15,516
  • 9
  • 57
  • 105
Afrobeta
  • 37
  • 6
  • I'm not a unity programmer, but it seems to me that if the script is started from a button, then the new file should also be created there. – Idle_Mind Apr 02 '19 at 00:31

1 Answers1

0

Use the following pattern (simplified):

using System.IO;

public class MyClass
{
    private Stream _stream;

    private void OnDisable()
    {
        _stream?.Dispose();
    }

    private void OnEnable()
    {
        _stream = File.OpenRead("file.txt");
    }

    private void Update()
    {
        if (_stream != null)
        {
            // do something with it
        }
    }
}
aybe
  • 15,516
  • 9
  • 57
  • 105