WriteInCSVNew.cs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using UnityEngine;
  2. using System;
  3. using System.IO;
  4. public class WriteInCSVNew : MonoBehaviour
  5. {
  6. public int index = 0;
  7. private string path;
  8. private float time;
  9. private GameObject[][] humansGO;
  10. private void Start()
  11. {
  12. humansGO = gameObject.GetComponent<InstantiatePrefab>().humanGameObject;
  13. string currentPath = Directory.GetCurrentDirectory();
  14. string reference = @"\Assets\CSV_files\";
  15. string directory = currentPath + @"\Assets\CSV_files";
  16. // create directory if not existing
  17. if (!Directory.Exists(directory))
  18. {
  19. Directory.CreateDirectory(directory);
  20. }
  21. // create file for path
  22. using (File.Create(currentPath + reference + "Walk" + index + ".csv"))
  23. {
  24. path = currentPath + reference + "Walk" + index + ".csv";
  25. }
  26. // write column name
  27. using (StreamWriter firstLine = new StreamWriter(path))
  28. {
  29. var line = string.Format("Delta Time;Human i;Human j;Position x;Position y;Position z;Rotation x;Rotation y;Rotation z;Rotation w");
  30. firstLine.WriteLine(line);
  31. firstLine.Flush();
  32. }
  33. }
  34. // Start is called before the first frame update
  35. private void FixedUpdate()
  36. {
  37. time += Time.deltaTime;
  38. if (File.Exists(path))
  39. {
  40. try
  41. {
  42. using (StreamWriter file = new StreamWriter(path, true))
  43. {
  44. for(int i = 0; i < humansGO.Length; i++)
  45. {
  46. for(int j = 0; j < humansGO[i].Length; j++)
  47. {
  48. // Save position of Human leaders in file
  49. Vector3 pos = humansGO[i][j].transform.position; // (x,y,z)
  50. Quaternion rot = humansGO[i][j].transform.rotation; // (x,y,z,w)
  51. var line = string.Format("{0};{1};{2};{3};{4};{5};{6};{7};{8};{9}",
  52. time, i, j, 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"));
  53. file.WriteLine(line);
  54. file.Flush();
  55. }
  56. }
  57. }
  58. }
  59. catch (Exception e)
  60. {
  61. throw new ApplicationException("Something went wrong by writing into a csv file: ", e);
  62. }
  63. }
  64. }
  65. }