WriteInCSVNew.cs 3.1 KB

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