MousePosition.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using System;
  2. using System.IO;
  3. using System.Reflection;
  4. using System.Text;
  5. using UnityEngine;
  6. public class MousePosition : MonoBehaviour
  7. {
  8. public string logFileName = "";
  9. // Get from LoggingManager
  10. private int ParticipantID;
  11. private string logPathFolder = "";
  12. private string logPath;
  13. private float time = 0f;
  14. private string[] buffer;
  15. private int index = 0;
  16. private void Start()
  17. {
  18. ParticipantID = gameObject.GetComponentInParent<LoggingManager>().ParticipantID;
  19. logPathFolder = gameObject.GetComponentInParent<LoggingManager>().LogPathFolder;
  20. logFileName = "log_" + ParticipantID + "_" + logFileName + ".csv";
  21. logPath = Path.Combine(logPathFolder, logFileName);
  22. using (FileStream stream = File.Open(logPath, FileMode.Create))
  23. {
  24. using (StreamWriter writer = new StreamWriter(stream))
  25. {
  26. writer.WriteLine(GetLogFileHeader());
  27. writer.Flush();
  28. }
  29. }
  30. Debug.Log("Created new Logfile " + logFileName);
  31. buffer = new string[1000];
  32. }
  33. private string GetLogFileHeader()
  34. {
  35. StringBuilder header = new StringBuilder("ParticipantID");
  36. header.Append(";Time");
  37. header.Append(";Position");
  38. return header.ToString();
  39. }
  40. private void FixedUpdate()
  41. {
  42. StringBuilder line = new StringBuilder();
  43. line.Append(ParticipantID);
  44. line.Append(";" + time);
  45. line.Append(";" + Input.mousePosition.ToString());
  46. buffer[index++] = line.ToString();
  47. if (index > buffer.Length - 1)
  48. writeFromBuffer();
  49. time += Time.deltaTime;
  50. }
  51. private void writeFromBuffer()
  52. {
  53. if (File.Exists(logPath))
  54. {
  55. try
  56. {
  57. using (StreamWriter writer = new StreamWriter(logPath, true))
  58. {
  59. for (int i = 0; i < buffer.Length; i++)
  60. {
  61. if (buffer[i] != null)
  62. {
  63. writer.WriteLine(buffer[i]);
  64. writer.Flush();
  65. }
  66. }
  67. buffer = new string[1000];
  68. index = 0;
  69. }
  70. }
  71. catch (Exception e)
  72. {
  73. throw new ApplicationException("Something went wrong by writing into a csv file: ", e);
  74. }
  75. }
  76. }
  77. private void OnApplicationQuit()
  78. {
  79. writeFromBuffer();
  80. }
  81. }