CameraPosition.cs 2.9 KB

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