WriteInCSV.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using UnityEngine;
  2. using System;
  3. using System.IO;
  4. public class WriteInCSV : MonoBehaviour
  5. {
  6. public int index = 0;
  7. private string path;
  8. private void Start()
  9. {
  10. string currentPath = Directory.GetCurrentDirectory();
  11. string reference = @"\Assets\Data_position\";
  12. string directory = currentPath + @"\Assets\Data_position";
  13. // create directory if not existing
  14. if (!Directory.Exists(directory))
  15. {
  16. Directory.CreateDirectory(directory);
  17. }
  18. // create file for path
  19. using (File.Create(currentPath + reference + "Walk" + index + ".csv"))
  20. {
  21. path = currentPath + reference + "Walk" + index + ".csv";
  22. }
  23. // write column name
  24. using (StreamWriter firstLine = new StreamWriter(path))
  25. {
  26. var line = string.Format("Position x;Position y;Position z;Rotation x;Rotation y;Rotation z;Rotation w");
  27. firstLine.WriteLine(line);
  28. firstLine.Flush();
  29. }
  30. }
  31. // Start is called before the first frame update
  32. private void FixedUpdate()
  33. {
  34. // Save position of Human leaders in file
  35. Vector3 pos = this.gameObject.transform.position; // (x,y,z)
  36. Quaternion rot = this.gameObject.transform.rotation; // (x,y,z,w)
  37. if (File.Exists(path))
  38. {
  39. try
  40. {
  41. using (StreamWriter file = new StreamWriter(path, true))
  42. {
  43. //
  44. var line = string.Format("{0};{1};{2};{3};{4};{5};{6}",
  45. pos.x.ToString("f6"), pos.y.ToString("f6"), pos.z.ToString("f6"), rot.x.ToString("f6"), rot.y.ToString("f6"), rot.z.ToString("f6"), rot.w.ToString("f6"));
  46. file.WriteLine(line);
  47. file.Flush();
  48. }
  49. }
  50. catch (Exception e)
  51. {
  52. throw new ApplicationException("Something went wrong by writing into a csv file : ", e);
  53. }
  54. }
  55. }
  56. }