简体   繁体   English

每次在单位3D中启用脚本时创建新的CSV文件

[英]Creating a new CSV file everytime the script is enabled in unity 3D

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. 我使用VR在Unity中创建了一个场景,我想跟踪用户的位置并将其保存为CSV文件。 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. 因此创建了一个脚本,通过Button上的简单OnClick事件启用和禁用脚本。

So I created a Script that enables and disables the script via a simple OnClick Event on a Button. 所以我创建了一个脚本,通过Button上的简单OnClick事件启用和禁用脚本。 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. 我遇到的问题是,每当我禁用脚本并再次启用它时,就不会创建另一个csv文件。

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. 但实际上我不知道如何解决这个问题,因为我不知道如何在每次再次启用脚本时创建一个创建csv文件的函数。

I would really appreciate it if somebody could help me. 如果有人能帮助我,我真的很感激。

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
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM