Hello,
SOMEONE PLEASE HELP!
I would like to know how I can add a new row to a csv file at every second or every 0.1 second. This would be helpful for my research in VR since I need to determine the headset position/rotation with respect to time when in play mode.
I developed the following code below to write the CSV file, however, it does not add new rows to the file at every second:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO; // Library that allows us to write to files
public class CSVWriter : MonoBehaviour
{
public float timer = 0.0f;
public float seconds = 0.0f;
private float xPos;
private float yPos;
private float zPos;
private float xRot;
private float yRot;
private float zRot;
string fileName = “”; // variable to store file name (declared in start())
[System.Serializable]
public class Player
{
public string ID;
public string name;
public string gender;
public string age;
}
[System.Serializable]
public class PlayerList
{
public Player[ ] player;
}
public PlayerList myPlayerList = new PlayerList();
// Start is called before the first frame update
void Start()
{
fileName = Application.dataPath + “/DataCollection.csv”;
}
// Update is called once per frame
void Update()
{
WriteCSV();
timer += Time.deltaTime;
seconds = Mathf.Round(timer);
}
public void WriteCSV()
{
if(myPlayerList.player.Length > 0) // check if there is a player in the player list
{
TextWriter tw = new StreamWriter(fileName, false); // opens the file and deletes everything prior
tw.WriteLine(“ID, Name, Gender, Age, Time, xPos, yPos, zPos, xRot, yRot, zRot”); // write the headings (“,” adds a column)
tw.Close();
tw = new StreamWriter(fileName, true); // reopen the file and append
for(seconds = 0; seconds < 60; seconds++) // for every second, add the following data to the file
{
tw.WriteLine(myPlayerList.player[0].ID + “,” + myPlayerList.player[0].name + “,” + myPlayerList.player[0].gender + “,” + myPlayerList.player[0].age + “,” + seconds);
}
tw.Close();
}
}
}