UISlider.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. using UnityEngine;
  5. public class UISlider : MonoBehaviour
  6. {
  7. // Inspector variables
  8. public string logFileName = "";
  9. // Get from LoggingManager
  10. private int ParticipantID;
  11. private string logPathFolder = "";
  12. // Changes on click
  13. private int sliderValue = 0;
  14. private string logPath;
  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. logPathFolder = gameObject.GetComponentInParent<LoggingManager>().LogPathFolder;
  22. logFileName = "log_" + ParticipantID + "_" + logFileName + ".csv";
  23. logPath = Path.Combine(logPathFolder, logFileName);
  24. using (FileStream stream = File.Open(logPath, 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 " + logFileName);
  33. buffer = new string[1000];
  34. }
  35. private string GetLogFileHeader()
  36. {
  37. StringBuilder header = new StringBuilder("ParticipantID");
  38. header.Append(";Time");
  39. header.Append(";Value");
  40. return header.ToString();
  41. }
  42. public void registerOnValueChanged(float value)
  43. {
  44. sliderValue = (int) value;
  45. }
  46. private void FixedUpdate()
  47. {
  48. StringBuilder line = new StringBuilder();
  49. line.Append(ParticipantID);
  50. line.Append(";" + time);
  51. line.Append(";" + sliderValue);
  52. buffer[index++] = line.ToString();
  53. if (index > buffer.Length - 1)
  54. writeFromBuffer();
  55. time += Time.deltaTime;
  56. }
  57. private void writeFromBuffer()
  58. {
  59. if (File.Exists(logPath))
  60. {
  61. try
  62. {
  63. using (StreamWriter writer = new StreamWriter(logPath, true))
  64. {
  65. for (int i = 0; i < buffer.Length; i++)
  66. {
  67. if (buffer[i] != null)
  68. {
  69. writer.WriteLine(buffer[i]);
  70. writer.Flush();
  71. }
  72. }
  73. buffer = new string[1000];
  74. index = 0;
  75. }
  76. }
  77. catch (Exception e)
  78. {
  79. throw new ApplicationException("Something went wrong by writing into a csv file: ", e);
  80. }
  81. }
  82. }
  83. private void OnApplicationQuit()
  84. {
  85. writeFromBuffer();
  86. }
  87. }