1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- using System;
- using System.IO;
- using System.Reflection;
- using System.Text;
- using UnityEngine;
- public class MousePosition : MonoBehaviour
- {
- public string logFileName = "";
- // Get from LoggingManager
- private int ParticipantID;
- private string logPathFolder = "";
- private string logPath;
- private float time = 0f;
- private string[] buffer;
- private int index = 0;
- private void Start()
- {
- ParticipantID = gameObject.GetComponentInParent<LoggingManager>().ParticipantID;
- logPathFolder = gameObject.GetComponentInParent<LoggingManager>().LogPathFolder;
- logFileName = "log_" + ParticipantID + "_" + logFileName + ".csv";
- logPath = Path.Combine(logPathFolder, logFileName);
- using (FileStream stream = File.Open(logPath, FileMode.Create))
- {
- using (StreamWriter writer = new StreamWriter(stream))
- {
- writer.WriteLine(GetLogFileHeader());
- writer.Flush();
- }
- }
- Debug.Log("Created new Logfile " + logFileName);
- buffer = new string[1000];
- }
- private string GetLogFileHeader()
- {
- StringBuilder header = new StringBuilder("ParticipantID");
- header.Append(";Time");
- header.Append(";Position");
- return header.ToString();
- }
- private void FixedUpdate()
- {
- StringBuilder line = new StringBuilder();
- line.Append(ParticipantID);
- line.Append(";" + time);
- line.Append(";" + Input.mousePosition.ToString());
- buffer[index++] = line.ToString();
- if (index > buffer.Length - 1)
- writeFromBuffer();
- time += Time.deltaTime;
- }
- private void writeFromBuffer()
- {
- if (File.Exists(logPath))
- {
- try
- {
- using (StreamWriter writer = new StreamWriter(logPath, true))
- {
- for (int i = 0; i < buffer.Length; i++)
- {
- if (buffer[i] != null)
- {
- writer.WriteLine(buffer[i]);
- writer.Flush();
- }
- }
- buffer = new string[1000];
- index = 0;
- }
- }
- catch (Exception e)
- {
- throw new ApplicationException("Something went wrong by writing into a csv file: ", e);
- }
- }
- }
- private void OnApplicationQuit()
- {
- writeFromBuffer();
- }
- }
|