ReadFromCSV.cs 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using UnityEngine;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System;
  5. [DefaultExecutionOrder(20)]
  6. [RequireComponent(typeof(InstantiatePrefab))]
  7. public class ReadFromCSV : MonoBehaviour
  8. {
  9. private Tuple<List<float>, List<Vector3>, List<Quaternion>, List<float>>[][] humansData;
  10. private void Start()
  11. {
  12. GameObject[][] humansGO = gameObject.GetComponent<InstantiatePrefab>().humanGameObject;
  13. humansData = new Tuple<List<float>, List<Vector3>, List<Quaternion>, List<float>>[humansGO.Length][];
  14. for(int i = 0; i < humansGO.Length; i++)
  15. {
  16. humansData[i] = new Tuple<List<float>, List<Vector3>, List<Quaternion>, List<float>>[humansGO[i].Length];
  17. for(int j = 0; j < humansData[i].Length; j++)
  18. {
  19. humansData[i][j] = new Tuple<List<float>, List<Vector3>, List<Quaternion>, List<float>>(new List<float>(), new List<Vector3>(), new List<Quaternion>(), new List<float>());
  20. }
  21. }
  22. }
  23. /// <summary>
  24. /// Reads from the given path the csv file
  25. /// </summary>
  26. /// <param name="path">The path were the csv file is located</param>
  27. /// <returns>A matrix of tuples with the following order in the tuple: time; Position; Rotation; Speed</returns>
  28. /// <exception cref="ApplicationException"></exception>
  29. public Tuple<List<float>, List<Vector3>, List<Quaternion>, List<float>>[][] ReadFromCSVFile(string path)
  30. {
  31. if(!File.Exists(path)) return null;
  32. try
  33. {
  34. using (StreamReader reader = new StreamReader(path, true))
  35. {
  36. // Skip header
  37. reader.ReadLine();
  38. while (!reader.EndOfStream)
  39. {
  40. var line = reader.ReadLine();
  41. var values = line.Split(';');
  42. /*
  43. * Value 0 : Time
  44. * Value 1-2: i,j
  45. * Value 3-5: Position
  46. * Value 6-9: Rotation
  47. * Value 10 : Speed
  48. */
  49. // Set i, j position in matrix
  50. int i = int.Parse(values[1]);
  51. int j = int.Parse(values[2]);
  52. // Add into timer list
  53. humansData[i][j].Item1.Add(float.Parse(values[0]));
  54. // Add into position list
  55. humansData[i][j].Item2.Add(new Vector3(
  56. float.Parse(values[3]),
  57. float.Parse(values[4]),
  58. float.Parse(values[5])));
  59. // Add into rotation list
  60. humansData[i][j].Item3.Add(new Quaternion(
  61. float.Parse(values[6]),
  62. float.Parse(values[7]),
  63. float.Parse(values[8]),
  64. float.Parse(values[9])));
  65. humansData[i][j].Item4.Add(float.Parse(values[10]));
  66. }
  67. }
  68. }
  69. catch (Exception e)
  70. {
  71. throw new ApplicationException("Something went wrong by reading from a csv file: ", e);
  72. }
  73. return humansData;
  74. }
  75. }